forms - Updating variable after AJAX call in jquery -
i want create page whether user makes selection on (django modelchoice) form , results in ajax update of form may trigger additional ajax update. rather rudimentary javascript skills not task!
the problem cannot correctly read value of updated form - 1 step behind think should be. in simplified example below, if jquery calculating value of second_var @ same time first_var (i.e before have updated ajax call). if keep switching between 2 options in #id_first_metric, second_var update pointing value of #id_second_metric before last update.
how can second_var correctly contain newly updated value?
function first_function(first_var){ console.log('first var:' + first_var); // correctly states value of first var var update_url = '/ajax/update_second_metric/first_var'; $('#id_second_metric').load(update_url); $('#first_metric_selector').change(function () { var first_var = $('#id_first_metric').val(); first_function(first_var); $('#second_metric_selector').change(); }); $('#second_metric_selector').change(function () { var second_var = $('#id_second_metric').val(); console.log('second var' + second_var); // fails detect new value of second var created first // ajax call });
answer
function first_function(first_var){ console.log('first var:' + first_var); // correctly states value of first var var update_url = '/ajax/update_second_metric/'; $('#id_second_metric').load(update_url, function(){ $('#second_metric_selector').change(); });
"$('#id_second_metric').load(update_url)" happens asynchronously. there no guarantee "$('#second_metric_selector').change()" called before "$('#id_second_metric').load(update_url)" finishes.
you can use callback function provided load guarantee order. see http://api.jquery.com/load/
Comments
Post a Comment