Reputation: 1271
I am trying to use ajax to get information from my server. the page xxx.php is a page with only 123 written on it. However, when I want to return the content of that page, it returns null.
function myFunct(){
$.ajax({
url: 'xxx.php',
success: function(data) {
return data;
}
});
}
var data = myFunct(); //nothing.
Upvotes: 5
Views: 14423
Reputation: 887453
AJAX is asynchronous.
You only get a response some time after the rest of your code finishes running.
Instead, you need to return the value using a callback, just like $.ajax
does:
function myFunct(callback){
$.ajax({
url: 'xxx.php',
success: function(data) {
// Do something to the data...
callback(data);
}
});
}
myFunct(function(result) {
...
});
Upvotes: 5
Reputation: 9724
You can use in synchronized mode (despite being recommended with async callback to avoid "freezing" of the code).
Using synchronized:
function myFunct(callback){
return $.ajax({
url: 'xxx.php',
async: false
}).responseText;
}
Upvotes: 1
Reputation: 494
Try to use a ajax error handling, for check your response
function myFunct(){
$.ajax({
url: 'xxx.php',
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus){
alert("Status: "+ jqXHR.status);
alert("textStatus: " + textStatus);
}
});
}
Upvotes: 0
Reputation: 14363
Please note that ajax is 'asynchronous'. So, the response to your server call may not received by the time myFunct() completes execution. You may put the logic of process the data from your server call in the 'success' of ajax.
function myFunct(){
$.ajax({
url: 'xxx.php',
success: function(data) {
// processMyData(data);
}
});
}
Upvotes: 8
Reputation: 2251
var globalVal;
function myFunct(){
$.ajax({
url: 'xxx.php',
success: function(data) {
alert(data); // you can see you data
globalVal= data;
}
});
}
// it is response to server, and response executed a bit latter that you assign value
myFunct(); //nothing.
alert(globalVal)
Upvotes: 0