I'm looking for a way to modify a variable declared outside of a callback, then use the modified variable after defining the callback. My intent is reflected in the code:
$('#my_form').submit(function() {
let my_condition
let data = $(this).serialize()
$.ajax({
method: 'POST',
url: '/my_url',
data: data
})
.done(function(json_response) {
if (json_response.my_variable) {
my_condition = true
}
else {
my_condition = false
}
})
// I'm looking for a way to guarantee `my_condition` is set by the AJAX before the below code is run.
if (my_condition) { // I know `my_condition` will be null because this line won't wait for the AJAX to finish and set `my_condition`.
return true
}
else { // The event handler will always hit this condition.
return false
}
})
I'm aware that I could add blocking sleep time before checking my_condition
to wait for the AJAX. This is not a solution I'm looking for. I'm also aware that I could set my_condition
based on inspecting data
on the frontend. However, for reasons specific to my use case, data
needs to be processed on the backend. Lastly, I want to avoid the AJAX setting async: false
.
I know why the code above does not work. My question is, is there some way to achieve the desired result? I have a feeling there might be a solution that uses Promise, but I don't see exactly how that would be done.
Edit 1: The specific use case is with regards to form submission. I want the submit handler to return true or false, i.e., submit via the form's action attribute (when my_condition is true) or a different (AJAX) route (when my_condition is false) based on backend processing results of data.
Edit 2: This is indeed a duplicate of Javascript - Stop form submit depending on ajax response [duplicate]