Recent Posts

How to return the response from an AJAX call

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // tried that one as well
        }
    });

    return result;
}

var result = foo(); // always ends up being `undefined`.
this is a bad usage of AJAX. A function with an AJAX call never return anything. but instead hand off the data to something called a callback function, which handles the data. For example:

function handleData( responseData ) {
    // do what you want with the data
    console.log(responseData);
}

$.ajax({
    url: "hi.php",
    ...
    success: function ( data, status, XHR ) {
        handleData(data);
    }
});
Returning anything in the submit handler will not do anything, it must instead either hand off the data, or do what you want with it directly inside the success function.

No comments:

Post a Comment