I have a very straightforward thing I am trying to do, but am new to Javascript.
I have an HTML page which generates a series of DIV elements with an ID that is dynamically generated.
Example: <div id="shots_234"></div>
, <div id="shots_256"></div>
I am making a jQuery AJAX request, and I want to populate the html with the response targetting one of those IDs.
function WeddingsShotDown(shotid, segmentid) {
document.getElementById('ShotDownId').value = shotid;
var form = document.getElementById('ShotDown');
var formData = new FormData(form);
var id = "shots_" segmentid;
var divid = document.getElementById(id);
console.log("Div: " divid);
$.ajax({
url: '/Weddings/ShotDown',
type: 'POST',
data: formData,
dataType: 'html',
processData: false,
contentType: false,
success: function (response) {
if (response) {
$("#shots_" segmentid).html(response);
document.getElementById('ShotId').value = "";
showNotification("success", "Your shot sequence has been updated", "far fa-check-circle");
} else {
showNotification("danger", "Error saving shot sequence", "far fa-check-circle");
}
}
});
}
So neither
$("#shots_" segmentid).html(response);
Nor
var id = "shots_" segmentid;
var divid = document.getElementById(id);
Get me the div that I want.
How can I update that element?
CodePudding user response:
- Var segmentid not exist in the success function. Try, save id in the request with beforeSend, and get in the receive:
$.ajax({
url: '/Weddings/ShotDown',
type: 'POST',
data: formData,
dataType: 'html',
processData: false,
contentType: false,
beforeSend:function( jqXHR ){
jqXHR.id = segmentid;
}
}).done(function(response, msgStatus, jqXHR){
if (response) {
$("#shots_" jqXHR.id).html(response);
document.getElementById('ShotId').value = "";
showNotification("success", "Your shot sequence has been updated", "far fa-check-circle");
} else {
showNotification("danger", "Error saving shot sequence", "far fa-check-circle");
}
});