Reputation: 22832
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
);
Upvotes: 0
Views: 197
Reputation: 91557
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:
getReturn(
function(return_value) {
if (return_value) {
$("#myForm").submit();
}
},
id,
old_variable);
return false;
Upvotes: 1
Reputation: 26773
You don't understand asynchronous execution. You can not return anything from $post! Do not forget that. All you can do is trigger execution of something - you can try to set a variable flag, but it won't help you. You also need to trigger the execution of a function that does something with that flag, and you have to call that function from inside $post.
The function you are sending in as the callback returns a value. But it does not return the value to anyplace. You are calling it inside $post, and it's returning the value inside $post - which does nothing useful for you at all since you aren't doing anything with the return value.
I would tell you how to change it, except you have not said what you want to do with this return value.
Upvotes: 1