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

Go To StackoverFlow.com

0

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;
        alert(response)
    });
    var xml;
    xml = $.parseXML(response);
    alert($(response).find("item").each(function () {
        $(this).attr("id")
    }));
}

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"?>
<root>
<collection collection="locationPoint">
    <item id="1">
        <latitude>23.4442</latitude>
        <longitude>51.2341</longitude>
    </item>

    <item id="2">
        <latitude>2849.24</latitude>
        <longitude>213.132</longitude>
    </item>
</collection>

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


1

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:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
    </head>
    <body>
        <div id="dc"></div>
    </body>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
                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) {
                    $('#dc').html('error');
                }
            });
        });
    </script>
</html>
2012-04-03 23:47
by Oscar


1

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


0

Take a look at XML manipulation with jQuery

2012-04-04 00:20
by Fatih