Reputation: 9
I am trying to store the results of the return ajax call as: var yValue that is usable in javascript, but the results returning for yValue is always 0.
<head>
$.ajax({
url: 'test2.php',
success: function(data) {
var yValue= data; // data contains value 1;
}
});
alert (yValue);
</head>
The results returned is always zero or null, and when i try to check for the value of data using an alert box, it is always 1.
Even when i used data as the result to store into my array"dynamicdata" that i have created, it will return a value of 0 or NULL:
var globalData = null;
$.ajax({
url: 'test2.php',
async: false,
success: function(data) {
globalData = data;
}
});
var j=j+1;
var CurrentDate1 = new Date((new Date()).getTime())
var hours=CurrentDate1.getHours()
var minutes=CurrentDate1.getMinutes()
var seconds=CurrentDate1.getSeconds()
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var timer=hours+":"+minutes+":"+seconds+"";
// remove the first element
dynamicdata.splice(0, 1);
// add a new elemez
dynamicdata.push([timer, globalData]);
Anyone can help?
Upvotes: 0
Views: 125
Reputation: 108480
You can add ascync: false
to the ajax call:
var yValue;
$.ajax({
url: 'test2.php',
success: function(data) {
yValue = data; // data contains value 1;
},
async: false
});
alert(yValue);
This is not recommended though. You might as well get your head around asynchronous calls in JavaScript, you will be using it a lot. Here is an example on how you can organize your code if you are uncomfortable with nesting functions:
$.ajax({
url: 'test2.php',
success: onReady
});
function onReady(data) {
// this is called when the ajax call is completed.
alert(data);
}
Upvotes: 1
Reputation: 1038720
I am trying to store the results of the return ajax
Don't try to fight against the asynchronous nature of AJAX (it's what the first letter of the acronym stands for). It is a battle that you will lose. If you want to do AJAX you should stop thinking and writing code in a sequential manner. You should use events. You subscribe for events (such as the success
callback of an AJAX call) and you consume the results only inside those events.
So in your case instead of trying to store the results inside a variable simply use those results inside the callback:
$.ajax({
url: 'test2.php',
success: function(data) {
// Here and only here you can hope to reliably use the results
// of an AJAX call
alert(data);
}
});
For completeness sake of the answer (not as something that you should ever do) you could set the async
flag to false
:
var globalData = null;
$.ajax({
url: 'test2.php',
async: false,
success: function(data) {
globalData = data;
}
});
alert(globalData);
Notice however that by doing this you are no longer doing AJAX. The call is not asynchronous. It is a standard synchronous call that will block the user browser during the processing. This completely defeats the whole purpose of AJAX. Don't do this.
Upvotes: 6