Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ajax requests on same event at same time . what should be the typical behaviour? how it is different if request is synchronous

In the following javascript code, I am sending two Ajax request at the same time.
After analysis using Firebug, I came to unusual conclusion that :
"which ever (Ajax) response is coming first is printing last".

Problem 2: if I assign the Ajax url destination to a random string (say "abcd") [which don't exist] then total number of ajax call will be increased to 3?

$(document).ready(function(e) {

  $("form[ajax=true]").submit(function(e) {

    e.preventDefault();

    var form_data = $(this).serialize();
    var form_url = $(this).attr("action");
    var form_method = $(this).attr("method").toUpperCase();

    $("#loadingimg").show();

    $.ajax({
      url: form_url, 
      type: form_method,      
      data: form_data,     
      cache: false,
      success: function(returnhtml){                          
        alert ("a");
        // $("#result").html(returnhtml); 
        // $("#loadingimg").hide();                    
      }           
    });   

    $.ajax({
      url: form_url, 
      type: form_method,      
      data: form_data,     
      cache: false,
      success: function(returnhtml){                          
        // $("#duplicate").html(returnhtml); 
        // $("#loadingimg").hide();
        alert("b");
      }           
    }); 
  });
});

Please refer the following Fiddle.

like image 613
atom217 Avatar asked Apr 10 '14 12:04

atom217


People also ask

What is the difference between synchronous and asynchronous requests in AJAX?

AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.

How do you make AJAX request synchronous?

Synchronous AJAX call is made when async setting of jQuery AJAX function is set to false while Asynchronous AJAX call is made when async setting of jQuery AJAX function is set to true. Default value of the async setting of jQuery AJAX function is true.

Is AJAX asynchronous or synchronous?

Ajax requests are Asynchronous by nature, but it can be set to Synchronous , thus, having the codes before it, execute first.

What is AJAX used for when working with asynchronous requests?

AJAX stands for Asynchronous JavaScript and XML. It is a set of web development to build more responsive websites and applications. AJAX allows web pages to update their content without users having to reload the page. AJAX is derived from JavaScript's function to allow for a more interactive experience.


2 Answers

Gaurav, you have an error, at the end of the 1st $.ajax it must end as ), and 2nd as ).

You can't end with ;

var result1;
var result2;
$.when(
    $.ajax({ // First Request
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){     
                result1 = returnhtml;                  
        }           
    }),

    $.ajax({ //Seconds Request
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){                          
            result2 = returnhtml;     
        }           
    })

).then(function() {
    $('#result1').html(result1);
    $('#result2').html(result2);
});
like image 198
GOAlves Avatar answered Oct 13 '22 17:10

GOAlves


I'm not sure I completely understand, but I will try to give you some information. Like David said It may seem that the first request is the last one responding, but that will vary under many circumstances. There are different ways you could do this to control the outcome or order of the requests.

1) Upon success of the first request you could initiate the second request. I don't recommend this for speed purposes as your requests aren't running in parallel.

$.ajax({ // First Request
    url: form_url, 
    type: form_method,      
    data: form_data,     
    cache: false,
    success: function(returnhtml){     
        $.ajax({ //Seconds Request
            url: form_url, 
            type: form_method,      
            data: form_data,     
            cache: false,
            success: function(returnhtml){                          
               // $("#duplicate").html(returnhtml); 
               // $("#loadingimg").hide();
                alert("b");
            }           
        }); 
       alert ("a");
       // $("#result").html(returnhtml); 
       // $("#loadingimg").hide();                    
       }           
    });   

2) If you need to have both requests responses at the same time, the preferred method would likely be jQuery deferred. This will make both requests run in parallel, and once both responses are received you can proceed as you would have.

Something Like this:

var result1;
var result2;
$.when(
    $.ajax({ // First Request
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){     
                result1 = returnhtml;                  
        }           
    }); 

    $.ajax({ //Seconds Request
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){                          
            result2 = returnhtml;     
        }           
    }); 

).then(function() {
    $('#result1').html(result1);
    $('#result2').html(result2);
});

Check out:

https://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.then/

https://api.jquery.com/deferred.done/

I hope this helps!

like image 33
wrxsti Avatar answered Oct 13 '22 16:10

wrxsti