Optimising AJAX calls

I'm quite new to AJAX (jQuery AJAX to be specific) and I want to post to a PHP function (through WordPress) 3 times. Instead of sending 3 POST requests, is there a way to just call merge the AJAX call?

Currently I have the following:

$.ajax({
    url: ajaxurl,
    async: false,
    cache: false,
    type: "POST",
    cache: false,
    data: { action: 'box', id: box_id, target: "float", value_aj: "none" }
});

$.ajax({
    url: ajaxurl,
    async: false,
    cache: false,
    type: "POST",
    cache: false,
    data: { action: 'box', id: box_id, target: "width", value_aj: "1499" }
});

$.ajax({
    url: ajaxurl,
    async: false,
    cache: false,
    type: "POST",
    cache: false,
    data: { action: 'box', id: box_id, target: "margin", value_aj: "auto"}
});

Surely there's a better way to do this? Basically the function that's receiving the data is just posting to a text file.

Sometimes without async it will only run the 3rd AJAX call too? So I put on async but obviously that will block until the 3 are done (which is bad).

Is there a more optimal way to do this within just one call?

Thanks.

Upvotes: 0

Views: 82

Answers (1)

aleha_84
aleha_84

Reputation: 8539

it is just the same as OP do, but async. And with use of ajaxSetup

$.ajaxSetup(
    {
        url: ajaxurl, 
        cache: false 
    }
);

$.ajax({
    type: "POST",
    data: { action: 'box', id: box_id, target: "float", value_aj: "none" }
    success: function(){
        $.ajax({
            type: "POST",
            data: { action: 'box', id: box_id, target: "width", value_aj: "1499" }
            success: function(){
                $.ajax({
                    type: "POST",
                    data: { action: 'box', id: box_id, target: "margin", value_aj: "auto"}
                });
            }
    });
    }
});

Upvotes: 1

Related Questions