function contents execution not in order - javascript

i have a java script function
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)

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]

Because AJAX is asynchronous (hence the name). The console log which logs "first ajaxRespose" is being executed before the AJAX request is completed and that's why you get undefined. Then the AJAX request completes and you get the response.

That is beacuse Ajax is Asynchronus....works happens “in parallel.”.. so when your Ajax call is getting executed, the other codes get executed parallely... the only way to make it work is to define it inside the callback function of ajax.callback function is executed when ajax call is completed thus getting the ajaxRespose in it

Related

AJAX delaying the execution of next lines

Given the following code, can anyone help me understand why the first alert is executed after the second one? I believe this happens because ajax has a small delay untill it fetches the data, correct me if i am wrong.Thanks in advance.
Javascript code:
window.onload = function() {
arry = new Array();
jQuery.ajax({
type: "GET",
url: "index.php?op=17&id=##postID##&action=fetch",
dataType: "text",
success: function(response){
var e = response;
console.log(JSON.parse(e));
arry = JSON.parse(e)
alert(e); //1st alert
}
});
alert("test") //2nd alert
}
The first "A" in AJAX stands for asynchronous. That means that it is not blocking in your code, so the alert('test') is called immediately after your AJAX request, whereas alert(e) is only called once the AJAX request has received a successful response from the server.
The 'small delay' that you mention is not such, but rather the time it takes for the server to execute whatever code and return a response.
If you absolutely need the request to be handled synchronously, you can pass the async property to the AJAX call as follows:
window.onload = function() {
var arry = [ ];
jQuery.ajax({
type: "GET",
url: "index.php?op=17&id=##postID##&action=fetch",
dataType: "json",
async: false
}).done(function(response) {
arry = response
alert(response); //1st alert
});
alert("test") //2nd alert
}
Notice that I have updated the code somewhat to use the done() promise. Also, specifying dataType: "json" negates the need to call JSON.parse() on the response text.
yous first array is inside the success event of the AJAX call which (the success function) gets registered, skipped and called back only when the response of the ajax call is ready..

Aborting / canceling running AJAX calls before execute new AJAX in JS

I've never done this type of manipulation of AJAX calls (to stop/abort/cancel or ignore? already running AJAX calls before the execution of a new one) before so I really don't understand how to do that and would appreciate some direction.
I have a page in my app where I make a number of AJAX calls to fill dynamically the data in my table (Object Name, Object Fit, Object Progress) when the page loads. For example, there are 5 rows in the table. So I call
$.post("/getFit", {objectId: objectId}, function (result) { manipulation with result }
and
$.post("/getProgress", {objectId: objectId}, function (result) { manipulation with result }
5 times each in the loop -- one for each of the objects.
The first column of my table has links to more detail on the object, and clicking on them I call another AJAX:
$(document).off('click', '.js_object').on('click', '.js_object', function (e) {
var objectId = $(this).attr("id")
$.post("/viewObject", {objectId: objectId}, function (result) {document.getElementById("main_window_content").innerHTML = result; });
})
The problem is that the browser will not render the results of the last AJAX call (/viewObject) until it has received the results of all of the previous calls (/getFit x5 and /getProgress x5).
As a result, a user that wants to drill into the detail on an object needs to wait until the AJAX calls for the other objects are complete before they see anything.
So I struggle with how to stop/abort/cancel (or ignore?) "/getProgress" and "/getFit" so we can fully execute "/viewObject" and view the results of it.
I would very much appreciate your help.
Use xhr.abort() to kill the xhr requests as shown in the below code in JS. I believe there is ajax.abort(); in JQuery
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
If you want execute one ajax after another, and you need all requests to work to show the final result, you can use .done():
$.ajax({
url:'/getFit',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /getProgress
$.ajax({
url:'/getProgress',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /viewObject
$.post("/viewObject"....
})
});
That way you only show /viewObject if the others calls were successfull

Jquery : Ajax is not been called first

I have a Jquery code which looks like below
function get_data_obj(){
var dataObj;
$.ajax({
url: "XXX.soesite.XXX",
success: function(result) {
dataObj = ['Hi'];
console.log("Inside ajax");
console.log(dataObj);
}
});
console.log("Outside ajax");
console.log(dataObj);
}
get_data_obj();
The output I am expecting is
Inside ajax
['Hi']
Outside ajax
['Hi']
But the output I am getting looks like this
Outside ajax
undefined
Inside ajax
['Hi']
I am really confused about the control flow of my function. Basically, my function was supposed ajax first and then print the other statements but unfortunately my function is not working as expected by me. Can anybody please tell me what's wrong in my code and how can I make my function to finish off ajax work first and then go further?
$.ajax is asynchronous be default if you don't specify otherwise.
if you want an operation to happen after the $.ajax request then you should include it in the done()/success()/fail() functions or set async to false.
function get_data_obj() {
var dataObj;
$.ajax({ url: "XXX.soesite.XXX", async: false, success: function(result) {
dataObj = ['Hi'];
console.log("Inside ajax");
console.log(dataObj);
}});
console.log("Outside ajax");
console.log(dataObj);
}
get_data_obj();
Please remember below when call ajax
Async:False(Default) = Codes paused. (Other codes are waiting for this..)
Async:True = Codes run parallel. Nothing get paused.
So jquery does not wait to complete the request first.
You can use the callback hooks provided by $.ajax()

javascript - variable scope

This is a silly question, but I'm trying to use the contents from var form_data outside the ajax scope. How would I go about doing this? form_data only seems to exist inside the ajax function rather than outside even after declaring the variable outside of the ajax scope. I thought variables bubbled up until it finds where it was declared when var isn't defined.
To clarify my question, how do I use the results from the server outside the success function? I don't want to limit myself to doing everything inside the ajax success callback.
$(function () {
var form_data;
$.ajax({
type: 'GET',
url: 'print_form.php',
data: {
//data sent to server
},
success: function (response) {
form_data = JSON.parse(response);
console.log(form_data); //object is printed out as expected
},
error: function () {
alert('AJAX failed for print_form');
}
});
console.log(form_data); //undefined
});
As AJAX stands for Asynchronous Javascript and Xml, so your code doesn't get blocked for an ajax operation being executed as it's asynchronous. In your case what happen is that when you are getting data through ajax your javascript doesn't stop continuing of execution and wait for the request to get success. Rather then that, while you are getting the data the rest of the code still gets executed. And that's why before you get the from the server through ajax request the form_data already gets printed outside of the ajax request scope.
Let's test it :
Try initializing form_data with any value. You'll find that now you won't get undefined outside the ajax where you printed the value. Rather you'll get the value you initialized the variable with.
An alternative construct to the success callback option, the .done()
method replaces the deprecated jqXHR.success() method. Refer to
deferred.done() for implementation details.
source: http://api.jquery.com/jquery.ajax/
Build your code as given in the docs:
I am having success with this setup that isolates the Ajax call.
function sendAjax(xhrdata) {
return $.ajax({
type: 'GET',
url: 'print_form.php',
data: xhrdata
}).promise();
}
sendAjax(data).done(function(response) {
form_data = JSON.parse(response);
console.log(form_data);
}

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Categories