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: function(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.logis called before you receive a result from ajax call. So your input changed, but not when you are outputting it. You can addasync:falseoption to$.ajax, and checkconsole.log– it will output the changed value