I have several HTML elements (buttons) that fire the same JQuery AJAX request. When the AJAX request returns successfully, I need to make some updates to the HTML element that triggered the AJAX request. I understand how to do this if I were to hardcode the id of the element to update, such as an item with an id of myDiv as shown in the code below, but I am unsure of how to handle a dynamic id that corresponds to the element that triggered the event.
$('body').on(
'click',
'#yt25',
function(){
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$('#myDiv').html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
I figure one option is to send the id of the HTML element that triggered the event as a key-value pair in the ajax request ‘data’ option and then have it passed back to the client as part of the AJAX response. I could then grab the id and know which HTML element to update. Is that the best way to handle this or am I missing something more obvious? Thanks.
You don’t need to sent it along with the ajax request.
This is one variation. You can also do this be assinging some classes to the element and get those elements by that class will do.