Jquery : Ajax is not been called first - javascript

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()

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..

store result ajax into variable not working

I'm trying to store ajax result into variable. When I use console.log it gives my html tag that I wanted, But when I trying set into global variable it said undifined.
How I can store ajax result into global variable
var result;
$.ajax({
url: "person.html",
success: function(data){
//result=data;
console.log(data);
}
});
//console.log(result);
Ajax is asynchronous, meaning that the code to find out what result IS is running at the same time that the console log of result, which is why you're getting undefined, because result hasn't been set by the time the value is being console logged.
The only way I know of to console log the result would be to either do it within the ajax success function or to have the ajax success function call a subsequent function that contains the console log. It's the only way to be sure that a value has been returned before you console log it.
Examples:
EXAMPLE 1:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
console.log(result);
//Note that in this instance using the variable 'result' is redundant, as you could simply console.log data like you're already doing.
}
});
EXAMPLE 2:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
subsequentFunction(result);
}
});
function subsequentFunction(result){
console.log(result)
}
// Note that if you're doing something simple with result that this could be a bit long winded and unnecessary.
It all depends on how much you're wanting to do with the result as to which option would be better.
Note: There is also a property of an ajax call called 'async' that you can set to false which forces it to be synchronous, but this is generally considered a bad idea as it will prevent any other code from running until the result is returned and locking the browser.
$.ajax returns a promise, meaning that your code KNOWS it's going to receive a response, but because it's dependent on an external source, it doesn't know when this response will come in.
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
See above link for more information on the subject.
ajax requests are async so your console.log(result) is running before getting response of your request. you should do something like this
var result;
$.ajax({
url: "person.html",
success: callback(data)
});
function callback (data){
result=data;
console.log(result);
}
You will not see anything beacuse the data is not populated yet. In your specific case you actually need to wait for the response. You can achieve it by using the following snippet.
$(document).ready(function(){
var data = $.parseJSON($.ajax({
url: 'person.html',
dataType: "json",
async: false
}).responseText);
var myProp = data.property; // Here you can access your data items
});
Another approach should be like you can push your data in an array and can access it in another function like this:
var result =[];
$(document).ready(function()
{
$.ajax({
url: 'person.html',
async:true,
dataType: "json",
success: function(data)
{
result.push(data);
}
});
});
NewFunction()
{
console.log(result);
}

Error when storing JSON after an ajax request (jQuery)

I'm quite new to JavaScript/jQuery so please bear with. I have been trying to store the resulting JSON after an ajax request so I can use the login info from it later in my program. I get an error stating that "Data" is undefined. Here is the problematic code:
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(){
var SessionData = Data();
(FunctionThatParsesJSON);
}
})
}
I have checked the URL manually and it works fine (including) being wrapped in the "Data" function. From what I have found online, this may be something to do with ajax been asynchronous. Can anyone suggest a way of storing the JSON so that I can use it later?
Try something like the following;
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(data){
functionToProcessData(data)
})
}
When making your ajax call, you can handle the response given by assigning a parameter to the function. In the case above, I have passed the 'data' parameter to the success function allowing me to then use it in further functions (as demonstrated by 'functionToProcessData(data)'.
The response from ajax call is captured in success handler, in this case 'data'.
Check below code:
success: function(data){
var SessionData = data.VariableName;
// Here goes the remaining code.
}
})
Since people ask about explanation, thus putting few words:
When we do $.ajax, javascript does the async ajax call to the URL to fetch the data from server. We can provide callback function to the "success" property of the $.ajax. When your ajax request completed successfully, it will invoke registered success callback function. The first parameter to this function will be data came from server as response to your request.
success: function ( data ) {
console.log( data );
},
Hope this helps.
Internally everything uses promises. You can explore more on promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Apparently you are using JSONP, so your code should look like this:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp",
success: function (data){
(no need to parse data);
}
});
Another option:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp"
})
.done(function (data){
(no need to parse data);
});
See the documentation and examples for more details.
success: function (data, textStatus, jqXHR){
these are the arguments which get passed to the success function. data would be the json returned.

$.ajax() success won't run function

My question regards the $.ajax() jQuery method. I can't get the success parameter in $.ajax() to work.
This works:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: window.alert("inside aJax statement")
});
This does not:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: function(){
window.alert("inside aJax statement");
}
});
In the first case, I get a JavaScript alert window that lets me know the $.ajax() I called is working. All that is changed in the second block of code is I put the window.alert() inside a function() { window.alert(); }.
The point of this is to verify that the $.ajax is running so I can put some actual useful code in the function(){} when the $.ajax runs successfully.
In your second example nothing will happen unless you get a successful call back from the server. Add an error callback as many here have suggested to see that indeed the ajax request is working but the server is not currently sending a valid response.
$.ajax({
type: "POST",
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType:"json",
success: function(response){
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
helpful Link in tracking down errors.
Your first example does nothing whatsoever to prove that the ajax call has worked. All it does is prove that the ajax function was reached, because the values of the properties in the anonymous object you're passing into the ajax function are evaluated before the function is called.
Your first example is basically the same as this:
// THIS IS NOT A CORRECTION, IT'S AN ILLUSTRATION OF WHY THE FIRST EXAMPLE
// FROM THE OP IS WRONG
var alertResult = window.alert("inside aJax statement");
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent=" + $('#wClient').val(),
dataType: 'json',
success: alertResult
})
E.g., first the alert is called and displayed, then the ajax call occurs with success referencing the return value from alert (which is probably undefined).
Your second example is correct. If you're not seeing the alert in your second example, it means that the ajax call is not completing successfully. Add an error callback to see why.
In first case window.alert is executed immidiatly when you run $.ajax
In second it run only when you receive answer from server, so I suspect that something wrong in you ajax request
You may want to try and use a promise:
var promise = $.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json'
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
What this does is saves the ajax call to a variable, and then assigns additional functionality for each of the return states. Make sure that the data type you are returning is actually json, though, or you may see strange behavior!
Note that js is single-threaded; the reason your first example works is because it actually executes the code next 'success' and stores the result. In this case there is nothing to store; it just pops an alert window. That means that the ajax call is leaving the client after the alert is fired: use the developer tools on Chrome or equivalent to see this.
By putting a function there, you assign it to do something when the ajax call returns much later in the thread (or, more precisely, in a new thread started when the response comes back).
I think that you do it right, but your request does not succeeds. Try add also error handler:
error: function(){alert("Error");};
I guess that dataType does not match or something like that.
It is 100% your second example is correct. Why it does nothing? Maybe because there is no success in the ajax call.
Add "error" handler and check waht does your ajax call return with the browsers' developer tool -> Network -> XHR . This really helps in handling of broken / incorrect ajax requests

function contents execution not in order

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

Categories