I have two .html, content.html and footer.html.
content.html
<div>
<div class="footer-content"></div>
</div>
footer.html
<div>copyright</div>
i made a ajax call for content.html, then i want to append the footer.html to the data(content), before showing it.
i have tried this.
$.ajax({
url: "filecheck.php", // Your server-side script
data: { file: filePath }, // Pass the file path to the server-side script
dataType: "html",
async: false,
success: function (data) {
if (data === "error") {
// If the server returns an error, redirect to 404
window.location.href = "pages/404.html";
return false;
} else {
// If the file exists, load the content
console.log(data);
if ($(data).find(".footer-content").length > 0) {
// Load footer using AJAX
console.log("put foote");
$.ajax({
url: "elements/footer.html",
success: function (footer) {
console.log("ok foot!");
$(data).find(".footer-content").append(footer);
//$(data)$('.footer-content', data).html(footer);
},
});
}
$("#content").html(data);
}
},
});
this code doesnt seem to work:
$(data).find('.footer-content').append(footer);
footer data wasn’t added to .footer-content
>Solution :
This is probably an issue of timing.
The second $.ajax() success callback completes after $("#content").html(data) is executed. jQuery’s .html() method sets string data via .innerHTML and won’t keep a reference to the $(data) document fragment; adding elements to data later will have no effect on the DOM.
The solution is to set your HTML data then find the relevant element within #content. If it exists, you can load extra HTML into it.
$("#content")
.html(data)
.find(".footer-content")
.load("elements/footer.html");
The .load() method will only run if the selector finds an element.