Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX returns null?

Tags:

jquery

ajax

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.
like image 499
user1710031 Avatar asked Dec 08 '22 20:12

user1710031


2 Answers

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);
        }
    });
}
like image 98
TJ- Avatar answered Jan 10 '23 04:01

TJ-


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) {
    ...
});
like image 39
SLaks Avatar answered Jan 10 '23 05:01

SLaks