I have the following submit handler which should lookup for some value based on the user input (key) and update an hidden field with the fetched value, before submitting the form.
$('#my_form').submit(function() {
$.ajax({
url: "lookup.php?key=" + $('#key').val(),", // Read one of the user input and lookup
dataType: 'json',
success: functio开发者_高级运维n(data){
console.log(data); // Shows the expected result
$('#my_form').find('input[name="xxx"]').val(data); // Substitute the hidden xxx with the fetched data
return true;
}
});
console.log($('#my_form').find('input[name="xxx"]')); // Still the old value here
return true;
});
Unfortunately, the final submitted form seems to contain the old value, as shown in the console.log. Given I'm very new to JS, I guess I'm missing something very basic here.
You make an asynchronous call, and your console.log
is called before you receive a result from ajax call. So your input changed, but not when you are outputting it. You can add async:false
option to $.ajax
, and check console.log
- it will output the changed value
$('#my_form').submit(function(e, skipAjax) {
if(typeof(skipAjax) == 'undefined') {
$.ajax({
url: "lookup.php?key=" + $('#key').val(),
dataType: 'json',
success: function(data){
$('#my_form')
.find('input[name="xxx"]').val(data).end()
.submit('skipAjax');
}
});
return false;
} else {
return true;
}
});
Hej the ajax call is async so it will not return and update your code before you submit the form.
What you need to do is to withhold submitting the form and submit it when the ajax call returns.
!Update to prevent inf loop
$('#my_form').submit(function(e) {
if($(this).find('input[name="xxx"]').val() === "") { // assuming its the default
e.preventDefault();
$.ajax({
url: "lookup.php?key=" + $('#key').val(),
dataType: 'json',
success: function(data){
$('#my_form')
.find('input[name="xxx"]').val(data).end()
.submit();
}
});
return false;
} else {
return true;
}
});
精彩评论