I have the following javascript
// JavaScript Document
$("[name=students]").each(function(){
var student_id = $(this).attr("data-student_id");
///////////////////////////////////////////////////////////////////
ajax_call = $.ajax({
method: "POST",
url: "/load.php",
dataType: "html",
async: true,
beforeSend: function(){
},
data: {
student_id: student_id
},
success: function( response )
{
// dynamically add radio buttons
// html response is radio buttons with NAME of as_xxxx inside of parent div[name=students] element already in the DOM
$("[name=students][data-student_id='"+student_id+"']").fadeIn( "slow").html(response).show();
},
error: function(xhr, textStatus, errorThrown)
{
// show error message
},
});
//END AJAX/////////////////////////////////////////////////////////////////
}).promise().done( function(){
save_data();
});
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// SAVE
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function save_data()
{
//$(document).on('click','[name=student][name^=as_]',function(event) // WORKS IF ajax ASYNC = TRUE
$("[name=student][name^=as_]").on("click",function(event) // DOES NOT WORK IF ajax ASYNC = TRUE. Works if ASYNC = FALSE
{
// SAVE RADIO BUTTON DATA ON CLICK
});
}
</javascript>
The code works fine if async is FALSE. But if asnyc is TRUE then I can't click any of the dynamically added radio buttons.
I am assuming that the promise().done code is firing BEFORE all the ajax synchronous requests are completed.
Is there a way to ensure a loops of synchronous ajax requests are completed?? OR why is the code not working?