0

i want to pass the return from a "child" (i don't know the correct term) function to the return in the parent function... how is the correct way to do this? check_data() isn't returning true or false

function check_data(type,field){
    var chkvalue = $(field).val();
    $.post("mods/ajax.fieldchk.php", {
        chkvalue: chkvalue,
        type: type
    },
    function(result){
        if(result==0){
            $(field).css({'background-color': '#faa', 'border': '1px solid #f00'});
            return false;
        }else if(result==1){
            $(field).css({'background-color': '#afa', 'border': '1px solid #0f0'});
            return true;
        }
    };
}

thnx

quakeglen
  • 165
  • 3
  • 7
  • 1
    You can't return from an asynchronous action such as `$.post()`. Read the topics above to learn about working with callbacks and Deferred objects. – Fabrício Matté Apr 06 '13 at 21:59
  • $.post is an asynchronous function by default, so your check_data function will exit before your expecting it – EmeraldCoder Apr 06 '13 at 22:00

1 Answers1

3

Since $.post is an asynchronous function you can't use it to return data on check_data. However you can pass some callback and execute with true/false argument.

Something like this:

function check_data(type,field,callback){
    var chkvalue = $(field).val();
    $.post("mods/ajax.fieldchk.php", {
        chkvalue: chkvalue,
        type: type
    },
    function(result){
        if(result==0){
            $(field).css({'background-color': '#faa', 'border': '1px solid #f00'});
            callback(true);
        }else if(result==1){
            $(field).css({'background-color': '#afa', 'border': '1px solid #0f0'});
            callback(false);
        }
    };
}
letiagoalves
  • 11,224
  • 4
  • 40
  • 66