I have one of those pesky variable scope problems with $.post. Before submitting a form, I want to first check if the user has edited the content. I return false if the user hasn’t.
I’ve looked at a bunch of different examples on Stackoverflow and the general way to do this is to create a function and a callback function inside that function to handle the callback. My problem is that the when I call getReturned below, the callback does not get implemented (know this because form gets submitted and I’ve tried an alert). Btw, alert("No changes were made so text was not submitted."); gets called successfully.
What am I doing wrong?
function getReturn(callback, id, old_variable){
var return_value = "ERROR";
$.post('myURL', {"id" : id},
function(data) {
var text_from_server = $.trim(data[0].note_text);
if (old_variable == text_from_server){
alert("No changes were made so text was not submitted.");
return_value = false;
callback(return_value);
} else {
return_value = true;
callback(return_value);
}
},
"json"
);
};
var id = 123;
var old_variable = "foo";
getReturn(
function(return_value){return return_value;/*alert("SUCCESS!");*/},
id,
old_variable
);
Since you are making an asynchronous request to test if the value has changed you have to always return false from your submit handler. In the callback, if the form was edited, you would then manually submit the form using
form.submit(). Something like this: