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..
Related
Can we programatically identify if a ajax call is executing in infinite loop.
Does it return any specific header when such thing happens? Can we identify this situation by headers in the response.
I have a set of ajax call and have taken care of most things, but still suspect that may be in some cases it might trigger infinite ajax call.
I make a set of ajax calls which are independent HTTP requests. I do certain calulcation of record processed by ajax call1 by sending another ajax call2.
$.ajax({
url:'<%= path1 %>',
method:"POST",
dataType: "script",
data: {
batch_id:<%= #id%>
}
});
$.ajax({
url:'<%= path2 %>',
method:"POST",
dataType: "script",
data: {
batch_id:<%= #id%>
}
});
Path 2 ajax calls are depended on path 1 ajax response. so if some varibales are not set properly when path1 ajax calls response or exception arise it may trigger unwanted behaviour or infinite ajax calls for path2 which will not understand when it has to stop since path1 ajax calls has ended abruptly.
instead of timeout is there a way from headers recived i can identify if a call is going around infinitely, so that i am sure that its not a long running request and that it needs to abort
Can anyone help?
The correct way would be to call second ajax only and only if the first one succeeded.
$.ajax({ url: path1,data: data }).done(function Ajax1Succeeeded() {
console.log("First done");
$.ajax({ url: path2, data: data }).done(function Ajax2Succeeeded() {
console.log("Both done");
})
}).fail(function Ajax1Error(){
console.log("First resulted in error");
});
EDIT: If your http requests are independent you could use promise
var ajax1 = $.ajax({url: path1});
var ajax2 = $.ajax({url: path2});
Promise.all([ajax1, ajax2]).then(function(response1, response2){
console.log("Both ajax call were successful");
}, function(){
console.log("There was an error");
});
You could use $.when()
$.when( $.ajax( "firstajax" ) ).then(function( data, textStatus, jqXHR ) {
// append data or what ever and then
//second ajax
});
the general rule is that the second ajax call should be done when the first one is finished. You can do it like this or simply add the second ajax call in the success method of your first one.
if your ajax call 2 totally depends on ajax call 1's success than you can execute your 2'nd ajax call only on success of 1'st ajax call success. use success method :
$.ajax({
url:'<%= path1 %>',
method:"POST",
dataType: "script",
data: {
batch_id:<%= #id%>
}
success : function (res){
secondAjax(); // call a function on success
}
});
function secondAjax(){
$.ajax({
url:'<%= path2 %>',
method:"POST",
dataType: "script",
data: {
batch_id:<%= #id%>
}
success : function(res){
alert('both ajax called successfully.');
}
});
}
I have requirement to manage 2 AJAX jQuery functions to start a process in the server and get the status from the server.
I,e. The first AJAX JQuery which will send a request to the server to start a particular process and returns back to the client with the status 'process-running'. The second AJAX JQuery function which will be called inside the success block of first function and its responsibility to query the status until it gets the response 'process-complete'.
Here is the psedo code I have
//This function which will be called on a button click
function buildApplication(){
//show the gif spinner in the front-end
$.when(buildApp()).then(function(result){
console.log('process-completed');
//hide the gif spinner in the front-end
});
}
function buildApp(){
return $.ajax({
type: 'POST',
url: 'url pointing to php script',
data: dataString,
cache: false,
success: function(result){
if(result == 'process-running'){
console.log('monitor starts');
getAppStatus();
console.log('monitor ends');
}
},
error: function(result){
}
});
}
function getAppStatus(){
console.log('Querying server');
return $.ajax({
type: 'POST',
url: 'url pointing to php script',
data: dataString,
cache: false,
success: function(result){
if(result == 'process-running'){
getAppStatus();
}
},
error: function(result){
}
});
}
The sleeping process is handled inside the PHP script of getAppStatus. I.e, If process is still running then the server will sleep for 10 seconds and then only returns response to the client.
The problem is both the functions are running asynchronous. That means the buildApp function invokes the getAppStatus function and just returns back immediately. The getAppStatus function runs as an orphan process.
How can I make it both synchronous (or similar) so that the parent caller will wait till the child to return back?
Note: I tried the async:false in the getAppStatus function but it freezes the browser and the ajax loader image stops spinning and it looks like hanged.
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
I'm relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code is not working.
I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's value as soon as the callback function is executed.
var array;
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
console.debug(array);
In the console, array appears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.
The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.
$(document).ready(function() {
var array;
var runLog = function() {
console.log(array);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
runlog();
}});
});
The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.
The success function doesn't execute immediately, but only after the HTTP-response arrives. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP-response data, do it from within the success function, or alternatively, define that operation inside of a function and then invoke that function from within the success callback.
Try calling a function to set this variable after your success:
var array;
var goodToProceed = function(myArr) {
console.debug(myArr);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
goodToProceed(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.
I'm relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code is not working.
I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's value as soon as the callback function is executed.
var array;
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
console.debug(array);
In the console, array appears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.
The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.
$(document).ready(function() {
var array;
var runLog = function() {
console.log(array);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
runlog();
}});
});
The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.
The success function doesn't execute immediately, but only after the HTTP-response arrives. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP-response data, do it from within the success function, or alternatively, define that operation inside of a function and then invoke that function from within the success callback.
Try calling a function to set this variable after your success:
var array;
var goodToProceed = function(myArr) {
console.debug(myArr);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
goodToProceed(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.