Home Multiple Async AJAX with jquery .append in it
Reply: 1

Multiple Async AJAX with jquery .append in it

Teodorus Teodorus
1#
Teodorus Teodorus Published in 2018-02-14 07:51:43Z

I have several ajax which append it result to HTML table. the example of code is like this

$.ajax({
    url: '<?php echo Url::toRoute('booking/get_1_rate'); ?>',
    type: 'GET',
    dataType: 'json',
    async: true,
    data:{          
    },          
    success: function(data){
         display_rate(data);
    }
}); 

$.ajax({
    url: '<?php echo Url::toRoute('booking/get_2_rate'); ?>',
    type: 'GET',
    dataType: 'json',
    async: true,
    data:{          
    },          
    success: function(data){
         display_rate(data);
    }
 });    

function display_rate(data)
{
    $.each(data.departure, function(index, value)
    {
        html_depart = "<tr><td>value.airline_code</td></tr>";
        $('#table_body_search_flights_depart').append(html_depart);
    });    
}

The problem is the result which appear in HTML table is depends on which ajax finish first, then the result of late ajax will not appear in HTML table. It seems like the jquery .append() just append the first ajax result.

I check the string that contain html in second ajax and its fine / success, but the string not append to html in second ajax. Only the string in first ajax that append to html

Is there any idea?

4cody
2#
4cody Reply to 2018-02-14 08:02:32Z

You can take a look at a few handy methods I found here : https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f

It will allow you to make multiple ajax calls and use appropriate promises in a few different ways.

The methods that seem to be of particular use to your situation might be the .done() and/or the .when() --

MULTIPLE AJAX CALLS

var a1 = $.ajax({...}),
    a2 = $.ajax({...});

$.when(a1, a2).done(function(r1, r2) {
    // Each returned resolve has the following structure:
    // [data, textStatus, jqXHR]
    // e.g. To access returned data, access the array at index 0
    console.log(r1[0]);
    console.log(r2[0]);
});

DEPENDENCE CHAIN of AJAX CALLS

var a1 = $.ajax({
             url: '/path/to/file',
             dataType: 'json'
         }),
    a2 = a1.then(function(data) {
             // .then() returns a new promise
             return $.ajax({
                 url: '/path/to/another/file',
                 dataType: 'json',
                 data: data.sessionID
             });
         });

a2.done(function(data) {
    console.log(data);
});

I've taken both of those examples from the link.

Hope that helps!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.3209 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO