How can i get the data from a AJAX request saved in a variable with jQuery?
3 Answers
var myvar;
$.ajax({
url: 'mything.php',
success: function(data) {
myvar = data;
}
});
3 Comments
Faizan Ali
its not working in my case. I need to store xml returned by soap api in variable. but its not storing
Faizan Ali
I need to access this variable outside this ajax request
AdrianoRR
Unless you set your ajax call to
async:false, your var won't hold that data by the time you use it.use this
var myvar='';
$.ajax({
type:'post',
url: 'your url',
dataType:'text',
success: function(data) {
useReturnData(data);
}
});
function useReturnData(data){
myvar = data;
console.log(myvar);
};
1 Comment
Matthew Zackschewski
This worked for me, thanks! I'm not sure why this is such a problem. I feel like I've assigned the variable directly in the async function but this time it just wasn't working. You helped!
How About This?
For Json Data:
var BaseConfig=$.ajax({
async:false,
url:'./config.php',
type:'get',
data:{'GetConfig':'YES'},
dataType:"JSON"
}).responseJSON;
And For Text Data:
var BaseConfig=$.ajax({
async:false,
url:'./config.php',
type:'get',
data:{'GetConfig':'YES'},
dataType:"TEXT"
}).responseText;