Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>By default $.ajax is asynchronous. In the options hash being passed, add</p> <pre><code>async: false </code></pre> <p>That will serialize the calls you are making having it perform the way you want.</p> <hr> <p>After getting comment from original poster, possible solution may be to do the following:</p> <ul> <li>Inside the submit call determine the number of calls that should be made.</li> <li>Store this result as a local variable within the handler function</li> <li>Create a callback on 'complete:' that will examine the value of the calls <ul> <li>If the number of calls to be made is greater than 0, then decrement the value and return</li> <li>If the number of calls reaches zero, update the window.location (really should use window.location.href as window.location is an object but browsers will allow this and perform correctly)</li> </ul></li> </ul> <p>Note, I don't have any information on the thread safety of performing this kind of operation so YMMV.</p> <hr> <p>Example Code:</p> <pre><code>$("#form").submit(function(eventObject){ var $ajaxFields= $(".friendName[value!='']").filter(function(index){ var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName',''); return ($("#"+idEmail+"[value!='']").length &gt; 0); }); var numberToSubmit= $ajaxFields.length; $ajaxFields.each(function(){ var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName',''); var name = $(this).val(); var email = $("#"+idEmail).val(); // Submit the ajax request $.ajax({ type: 'POST', url: 'ajax/url', data: { name: name, email: email }, success: function(json) { // Log a console entry if our ajax request was successful console.log(name + " was submitted via ajax"); }, error: function(jqXHR, textStatus, errorThrown) { console.log("call not completed: "+textStatus); }, complete: function(jqXHR, textStatus) { if( --numberToSubmit == 0 ) { window.location.href= '/thanks'; } } }); }); // Prevent default form submission return false; }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload