jquery - javascript: returning a bool -


i have written jquery / js function "runs php query".

function runquery(op){ if(op.type == "edit"){     var b = false;     if(op.id != "" && (op.fromsong || op.tosong || op.when || op.comment)){     $.post("processor.php", { id: op.id, type: "edit", fromsong: op.fromsong, tosong: op.tosong, when: op.when, comment: op.comment }, function(data){         if(data == true){             console.log(true);             b = true;         }else{             console.log(false);              b = false;         }     });     }     return b; } 

i want return true of false depending on server answers. i'm sure php script working correctly , returning true or false correctly. every time run function console.log() outputs correct value, unlike variable b. seems alway false. doing wrong?

since .ajax() call ($.post wrapper $.ajax) runs asyncronously, variable b return false. best thing "workaround" pass in callback:

function runquery(op, callback){     if(op.type == "edit"){         if(op.id != "" && (op.fromsong || op.tosong || op.when || op.comment)){             $.post("processor.php", { id: op.id, type: "edit", fromsong: op.fromsong, tosong: op.tosong, when: op.when, comment: op.comment }, function(data){         if(data == true){             console.log(true);             callback.apply(this, [data]);         }else{             console.log(false);             callback.apply(this, [data]);         }      });     } }  runquery({     type: 'edit', }, function(data) {    alert(data); }); 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -