Append a load() output to the same div in jQuery Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Append a load() output to the same div in jQuery without wasting too much if your time.

The question is published on by Tutorial Guruji team.

A button calls a JS function that loads a different PHP page asynchronously using jQuery load, and it will put the result in a errorReturn div.

<div id='errorReturn'></div>
<button onclick='trySomething()'>Click me</button>

<script>
function trySomething() {
  var url = 'otherpage.php'
  $('#errorReturn').load(url)
}
</script>

All is fine.
Since I want the user to see ALL the errors if the button is clicked multiple times, I wanted to APPEND that result to the same div.
I tried both

$('#errorReturn').append.load(url)
$('#errorReturn').append(load(url))

And they didn’t work. Then I found the solution:

$('#errorReturn').append($('#errorReturn').load(url))

It works. Kind of 🙁 It fills the errorReturn div, but it doesn’t append to it. It simply overwrites it, as if I simply wrote

$('#errorReturn').load(url)

I should probably just take a break, but I cannot see what’s wrong 🙁

EDIT: Since somebody flagged this as “answered in another question”, the other question was using JS while I was explicitly asking for jQuery – plus the other answer generated a lot of fuss about adding HTML with possible XSS injection and I think the accepted answer here is way nicer and simpler to understand

Answer

load() always overwrites the content of the target element. To do what you require you could make the AJAX request and append the content manually. Try this:

<div id="errorReturn"></div>
<button id="add-content">Click me</button>
jQuery($ => {
  $('#add-content').on('click', e => {
    $.ajax({
       url: 'otherpage.php',
       success: html => $('#errorReturn').append(html)
    });
  });
});
We are here to answer your question about Append a load() output to the same div in jQuery - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji