Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure code runs before window.location.href

I have a submit event so that when a form is submitted I make an AJAX API call to POST some information and then I want to run code within that success handler that tracks information in Mixpanel and then redirects the page. I currently have it where the page just redirects by itself without submitting the Mixpanel information.

I commented out the window redirect and then the mixpanel stuff starts getting logged.

Here is my code:

$.post('record', Record, function(data) {
    mixpanel.identify(data.user);
    mixpanel.people.set({
      '$email': data.user.email
    });
    return mixpanel.track('Event Created', {
      'User': data.user.email,
      'Event Date': Date.now(),
      'Event Name': $('#record-title').val()
    });

    // this ends up submitting without the mixpanel stuff submitting
    window.location.href = "https://" + window.location.host + "/records/dashboard";
});

What is the best way to make sure that the mixpanel stuff gets sent and then the window.location happens.

like image 727
luke Avatar asked May 06 '26 08:05

luke


1 Answers

need to wait on mixpanel.track to finish

you can use the callback argument

If provided, the callback function will be called after tracking the event.

$.post('record', Record, function(data) {
    mixpanel.identify(data.user);
    mixpanel.people.set({
      '$email': data.user.email
    });
    mixpanel.track(
      // event name
      'Event Created',
      // properties
      {
        'User': data.user.email,
        'Event Date': Date.now(),
        'Event Name': $('#record-title').val()
      },
      // callback
      function () {
        window.location.href = "https://" + window.location.host + "/records/dashboard";
      }
    );
});
like image 181
WhiteHat Avatar answered May 08 '26 12:05

WhiteHat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!