Question

I use a jQuery.get() request to send a form data. But often the page reloads/redirects too fast, before my JavaScript/jQuery code catches and sends the form data to where i need. I use alert() to get the ajax request done while the user clicks ok on alert. Now i need the form working as usual (with PHP post and redirect) and to send the form data using jQuery or JavaScript BEFORE the page reloads and NO alerts. Is there any elegant way to make the page wait until jQuery is done with the request (without using alert)?

jQuery('#form').live('submit', function() {
    var inputValue = jQuery(this).find('#theInput').val();
    jQuery.get('http://someurl.com/order?var=' + inputValue);
    //alert('an unwanted alert');
});

UPD: I embed jQuery code through Google Tag Manager's iframe. So I can't change the way the form works. And I shouldn't prevent the form from submitting.

Was it helpful?

Solution

jQuery('#form').live('submit', function(e){
    e.preventDefault(); // prevent default behaviour

    var inputValue = jQuery(this).find( '#theInput' ).val();
    jQuery.get('http://someurl.com/order?var=' + inputValue, function(){
          // redirect
    });
    //alert('an unwanted alert');
});

OTHER TIPS

I would take a look at [done][http://api.jquery.com/deferred.done/] which could probably do what you want it to do. .done() will wait for the entire ajax to finish, and then run whatever function you call within done.

You can bind callback to do redirect and return false; to prevent default redirect shown as below:

jQuery('#form').on('submit', function() {
    var inputValue = jQuery(this).find( '#theInput' ).val();
    jQuery.get('http://someurl.com/order?var=' + inputValue,
        function(data){
            //write redirect code here. In case if you want to check response, you can get it in data variable.
        });
    return false; //prevent default redirect action
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top