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

Viewed 656

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

2 Answers

Make a new <div>, .load() content into it, and .append() that.

$("#errorReturn").append($("<div/>").load(url));

You can of course also add styles etc. to the <div>, like for example a top margin to separate the individual errors.

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)
    });
  });
});
Related