2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot it's working and what I did is what I learned from infinite skills course but turned out that it's wrong. Thank you.
Wrap your XML response with one more root node and you will be able to use find('user').

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.