Sonic Soul
Sonic Soul

Reputation: 24909

calling jQuery.ajax consecutively results in single callback

this is a interesting problem.

i am doing an asynchronous ajax put

    return $.ajax({
        url: url,
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        async: true, // default
        success: function (result, textStatus, xhr) {...}

this works as expected, unless a user does a put before previous call returns (even though it's async, the call does take .5 second to complete)

if a user presses the button a few times (executing multiple puts) the following happens:

this leads me to inevitable conclusion that the first server callback triggers all outstanding callbacks..

i could disable the button until the callback returns, but is it possible to handle multiple outstanding calls? is this a browser limitation? best way to handle this?

UPDATE

as a test i switched to using POST instead of PUT: adjusted type: 'POST' on JS side, and [HttpPost] on web api (server side).

the behavior did not change.

UPDATE

looking at posts like this one.. this really should work. i don't see any specific reason why the rest of concurrent requests are not not making it out to the server.

Upvotes: 5

Views: 219

Answers (2)

Mr.G
Mr.G

Reputation: 3559

You can't wait for an async callback in javascript. You have to restructure your code to do all future work based on the async response from the actual callback.

If you need to make multiple consecutive ajax calls, then you issue the first one and in the success handler or response handler for the first ajax call, you issue the second ajax call and in the response handler for the second one, you carry out whatever you want to do with the data

Upvotes: 0

Jesse Bunch
Jesse Bunch

Reputation: 6679

Shouldn't PUT requests be idempotent? That is, submitting multiple requests should generate the same response? If so, the code may simply be trying to coalesce your identical PUT requests since they should all end up with the same result. If you're incrementing some ID for every post (i.e. changing server state) then you should be using POST instead of PUT.

This may not fix your issue; it's just a thought.

Upvotes: 1

Related Questions