Home > DeveloperSection > Forums > function contents execution not in order
Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    April-02-2013 2:36 AM

 JavaScript
Ratings:


 1 Reply(s)
 668  View(s)
Rate this:
Hi Expert!

I have a javascript function as below

function myfunction() {

    var url = location.href;
    var ajaxRespose;

        $.ajax({
            type:"GET",
            url: url,
            cache:false,
            dataType: "text",
            success: function(response) {
                var data = $.parseJSON(response);
                ajaxRespose = data;
                console.debug("ajaxRespose ==>:"+ajaxRespose);
            }
        });
        console.debug("first ajaxRespose: " +ajaxRespose);
    }
    return false;
}
on my console (firbug) i get :

first ajaxRespose: undefined

ajaxRespose ==>:[object Object]
My question is, why the ajax call execute after the "first" console.debug. PS: i have simplified the function, (function works ok, but problem is in 

sequence of execution)

Thanks in advance!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-02-2013 7:33 AM

Hi Ankita!

Because $.ajax() is asynchronous, the sequence of events happen like this:

$.ajax(...);   // executes AJAX request
console.debug("first ajaxResponse:" + ajaxRespose);   // undefined

/* some time later, we receive AJAX response */

// it executes the success function from the original AJAX request
console.debug("ajaxRespose ==>:"+ajaxRespose);  // [object Object]

Don't want to miss updates? Please click the below button!

Follow MindStick