AL DI
AL DI

Reputation: 560

Are multiple simultaneous Ajax request possible?

I am new to jquery and Ajax and I have the following question.

Are multiple Ajax request allowed? I use PHP and I would like to have form submit via jquery Ajax and at the same time trigger another Ajax request that would do another task. All of this without the user waiting for every request to complete.

Is this possible?

Thanks for the help guys!

* Edit * I tried it but if i try to redirect the browser to another page it waits until ajax completes before moving on.

this is the code for my test.

   /* populate subcategory dropdown based on category select */
$('#categoria-selector').change(function (e) {
    var cat = $("#categoria-selector option:selected").text();
    alert(cat);

    $.ajax({
        type: "POST",
        url: baseurl + 'precios/test',
        success: function (data, status, xhr) {
            alert('second alert');
        }
    });

    $.ajax({
                type: "POST",
                url: baseurl + 'precios/test2',
                success: function (data, status, xhr) {
                    alert('third alert');
                }
            });
});

On my controller i have the following functions

 function test() {
        //sleep for 5 seconds
        $first = date('Y-m-d H:m:s');
        sleep(10);
        $second = date('Y-m-d H:m:s');
//start again
        $_SESSION['mivar'] = 'Started at ' . $first . ' and ended at ' . $second;
    }

    function test2() {
        //sleep for 5 seconds
        $first = date('Y-m-d H:m:s');
        sleep(30);
        $second = date('Y-m-d H:m:s');
//start again
         $_SESSION['mivar2'] = 'Started at ' . $first . ' and ended at ' . $second;
    }

Upvotes: 1

Views: 2482

Answers (2)

Chris
Chris

Reputation: 388

Yes, you can have multiple simultaneous ajax requests.

The browser limits how many simultaneous requests you can make to a single domain, so each browser has a different limit. Most browsers limit the max number of simultaneous requests to 6. ( http://www.browserscope.org/?category=network )

Edit - For your output, what timestamps are you seeing? Is it possible this is a server-side issue? eg. you're using a single-threaded (dev) server that is only processing a single ajax request at a time?

It's also possible to abort ajax requests, so if you needed to cancel an existing one, you could do so. This post has more details: Abort Ajax requests using jQuery

Upvotes: 4

user3277192
user3277192

Reputation:

You can do ajax in parallel. It's the purpose of it all.

But you should not try to "redirect the browser to another page" with the response to a ajax call. You return data to the javascript and it acts on it.

Upvotes: 1

Related Questions