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.
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);
}
});
}
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) {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With