How to jQuery an XML file over a PHP-script and parse it right?

Go To


I already tried several methods getting my xml-script parsed in java, but i can't figure it out!

I have 2 files. mysql_get.php is returning an XML script if it is called. post_alert.html is fetching the XML script from mysql_get.php over jQuery $.post(..) as shown below:

function init2() {

    var response;
    $.post("mysql_get.php", function (data) {
        response = data;
    var xml;
    xml = $.parseXML(response);
    alert($(response).find("item").each(function () {

After hit a button which call init2(), i get the response message in xml style as i can see by the alert popup.

<?xml version="1.0" encoding="uft-8"?>
<collection collection="locationPoint">
    <item id="1">

    <item id="2">

But the alert doesn't popup "1" in addition as I wished for correct parsing.

What am I doing wrong?

2012-04-03 22:43
by Yannick Wald


Here are a couple of things: Line 1 of you xml file should read UTF-8 not UFT-8 Line 2 should be deleted, else make sure you have a closing tag, invalid xml

Then here is a little example that I hope helps:

        <script type="text/javascript" src=""></script>
        <div id="dc"></div>
    <script type="text/javascript">
        $(document).ready(function() {
                url: 'mysql_get.php',
                type: 'post',
                dataType: 'xml',
                success: function(data) {
                    $(data).find('item').each(function () {
                        $('#dc').append($(this).attr('id') + '<br/>')
                error: function(data) {
2012-04-03 23:47
by Oscar


The A in AJAX stands for asynchronous. The code after $.post(..) is executed right after $.post is called, regardless of the response state.

You have to move the var xml..-code inside the $.post call.
Also, .each() only loops through the elements, without returning the IDs. Use .map() to create an object consisting of the ids, and .toArray() to get an array representation of it.

function init2() {
    $.post("mysql_get.php", function(data) {
        var response = data;
        var xml = $($.parseXML(response));
        alert(response.find("item").map(function () {
            return $(this).attr("id")
        }).toArray() );
2012-04-03 22:57
by Rob W


Take a look at XML manipulation with jQuery

2012-04-04 00:20
by Fatih