Reputation: 1472
i am using a ajax function in which i pass a hidden field value and according to that the value is passed on to the next file and a query runs retuning a value (html) which i update later on to that hidden field but the problem is when i use that updated value of hidden field to pass on through a variable it dosent takes the new value updated instead it takes the old value of hidden field ? can anyone help me with this
var pre_prod_id = $('.prod_id').val(); //old hidden field value
$.ajax({
type: "GET",
url: "eg",
cache: false,
success: function(html) {
$('.prod_id').val(html); // got updated value via ajax and updated
}
});
var prod_id = $('.prod_id').val(); // getting new value of hidden field
alert(prod_id); // alert gives still the old value ???
$target = 'egab=' + abd + '&& abc=' + abc + '&& action=' + action + '&& prod_id=' + prod_id;
i have mentioned at steps what i am trying to do ? hope someone finds a solution to this.
Upvotes: 1
Views: 2684
Reputation: 20254
The call to $.ajax is asynchronous, so your code won't wait until a response has been received from the server before executing the second var prod_id = $('.prod_id').val();
statement.
The only way to be sure that a piece of code will run after the response to the Ajax call has been received, and not before, is to place it inside the 'success' function.
An alternative approach (but not one I would recommend) would be to make the ajax call synchronous by setting async : false. This is bad practice however, since it can make the browser unresponsive - I would recommend refactoring the code as described above.
Upvotes: 2