FUNCTION CONTENTS EXECUTION NOT IN ORDER

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
 889  View(s)
Ratings:
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!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: function contents execution not in order

    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]

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!