Question

I currently have the following code :

function Parse_Error(ErrMsg) {

$.post("ajax/errormsg.php", {
    errmsg: ErrMsg} 
    , function(data) {
    alert (data);
                return (data);
});
}

The alert will show me the correct message, but the function doesn't return the message. The function kept returning "undefined" but the alert is working perfectly. I've triedto add the following :

var tmp = data;
return tmp;

Without success.. Where did I go wrong?

Was it helpful?

Solution

The problem is the return statement isn't returning for the Parse_Error function. It's returning for the so-called anonymous function you declare (function(data){...}) which gives the data to JQuery, which it effectively ignores. Instead, you need to do something like this:

// your code that does the query
do_error_query('The Error Message');

function do_error_query(ErrMsg) {
    $.post("ajax/errormsg.php", {errmsg: ErrMsg} , function(data){

        alert(data);
        // here you need to call a function of yours that receives the data.
        // executing a return statement will return data to jquery, not to the calling
        // code of do_error_query().
        your_function(data);

    });
}

function your_function(data){
    // process the data here
}

The problem is that the call to do_error_query() completes BEFORE the result from the PHP page even comes back. So there is no way the result could possibly be returned. In other words, your_function(data) would be called well after do_error_query() returns. I hope that makes sense.

Effectively, do_error_query() is merely setting up an event handler. It cannot return the value, because the event has not completed yet. That is what the event handler, your_function(data) is for. It handles the event, the returning of data from your PHP page. While the event is yet to complete, do_error_query() will have long finished.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top