CHANDRA
CHANDRA

Reputation: 4928

Issue to invoke jquery ajax within the another ajax success

I have the following code within the ajax success function.

$.each(data,function(index,element){                            
$.ajax({                
            type: 'GET',                    
            url: "http://192.168.1.56/SampleAjaxCall/sample.svc/sampleFunciton",                    
            contentType: 'application/json; charset=utf-8',
            dataType: 'jsonp',
            async: false,
            success:function(response){ 

                    alert("Success !");   // invokes after the loop     
            }           
        }); 

        alert("After the ajax call");     // invokes first
});

First i am getting this alert message After the ajax call. after the loop end i am getting this alert message alert("Success !"). So the ajax is invoked after the loop end. So i need to invoke the ajax first. How to achieve this scenario.

Upvotes: 0

Views: 55

Answers (2)

Mike C
Mike C

Reputation: 3117

According to jQuery.ajax docs, dataType: "jsonp" requests do not support synchronous operation, so async: false is not going to work. You need to do it as giorgio describes.

Upvotes: 0

giorgio
giorgio

Reputation: 10212

Actually, your ajax call is in fact invoked before the second alert message ("After the ajax call"). But, as AJAX stands for Asynchronous etc. etc, while the ajax request is being processed, the rest of the script is executed already. So if you want the code being executed after the ajax call, wrap it in a function, and call that function in the success block (or just move the code into the success callback). Example:

var after_call_func = function() {
    alert("After the ajax call");
};

$.each(data,function(index,element){                            
    $.ajax({                
        // your ajax configuration
        success:function(response){ 
            alert("Success !");
            after_call_func(); // call the function when ajax is complete
        }           
    });
});

EDIT

I now notice you have the async option set to false, which is most probably why you'd expect the alert to execute AFTER the ajax call in the first place... But, as the jQuery documentation tells us:

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

And it looks like you have both... So either don't use a jsonp datatype nor a cross-domain request, or wrap the code to be executed after the ajax call in the success block, as in the example above.

Upvotes: 4

Related Questions