PHP User
PHP User

Reputation: 2422

empty data error with ajax xml

I'm having a simple php page the echo simple xml data like this

<user>
<username>jack</username>
<userage>20</userage>
</user>
<user>
<username>sally</username>
<userage>30</userage>
</user>
<user>
<username>steph</username>
<userage>40</userage>
</user>

and using this jquery code to display these information inside a div after clicking a button like this

$(document).ready(function(){

    $("#get").on('click',function(){

            $.get('dataxml.php',function(data){

                var str = '';
                $(data).find('user').each(function(){
                    var uname = ''; var uage = '';
                    $(this).find('username').each(function(){
                        uname = $(this).text();
                    });
                    $(this).find('userage').each(function(){
                        uage = $(this).text();
                    });
                    str += "<div><p class='uname'>"+uname+"</p><p class='uage'>"+uage+"</p></div>";
                });
            console.log(str);

            $("#result").html(str);
        });
    });
});

console says 'empty string' but when i view the console data i get this as in the image and the #result div is empty. So what's the error and how can I fix it?

enter image description here

Upvotes: 2

Views: 440

Answers (1)

dfsq
dfsq

Reputation: 193311

When you use

$(data).find('user')

it yields nothing because user are a root nodes of your XML document (technically the structure is not valid XML).

You can instead go with

$(data).each(function() {
    // ...
});

directly to iterate over username nodes.

The best thing to do however is to wrap entire response with some node so the XML will become:

<users>
    <user>
        <username>jack</username>
        <userage>20</userage>
    </user>
    <user>
        <username>sally</username>
        <userage>30</userage>
    </user>
    <user>
        <username>steph</username>
        <userage>40</userage>
    </user>
</users>

Then you will be able to use $(data).find('user').

Demo: http://plnkr.co/edit/7CquZyDTPFWbROgZWVP1?p=preview

Upvotes: 2

Related Questions