black_yurizan black_yurizan - 5 months ago 8
jQuery Question

'Junk after document element' error in AJAX request

I'm trying to practice using AJAX with jQuery, but when I am trying to call the XML file I get an error saying 'Junk after document element'. The line it is pointing to is number 3, but I don't see anything wrong with line 3.

The XML AJAX request was working when I only had the

<life>
tag in the XML file but when I added other tags it started to give me this error.

<?xml version="1.0" encoding="UTF-8"?>
<life>this is text</life>
<people> This is people</people>
<h2> this is a paragraph</h2>


<div id="ex1">
<h2>Example 1</h2>
<p></p>
<h4>results:</h4>
<button id="btn">Click for AJAX</button>
</div>


$(document).ready(function() {
$("button#btn").click(function() {
let p = document.createElement('p');
$('div#ex1').append(p);
$.ajax({
url: 'sample.xml',
success: function(data) {
$('div#ex1 p:last').append(data.querySelector('h2').innerHTML);
}
});
});
});

Answer

You have multiple "root" elements in your XML... Try something like the following...

<?xml version="1.0" encoding="UTF-8"?>
<content>
<life>this is text</life>
<people> This is people</people>
<h2> this is a paragraph</h2>
</content>
Comments