AJAX / Jquery XML parse

StealthRT picture StealthRT · Apr 19, 2012 · Viewed 80.8k times · Source

I try parsing the following type of XML (data from getMembers.php):

<?xml version="1.0" encoding="ISO-8859-1"?>
<members>
   <id>3422345</id>
   <name>Bill Gates</name>
   <id>232311</id>
   <name>Bob Barker</name>
</members>

And I use the code below to parse it:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "getMembers.php",
            cache: false,
            dataType: "xml",
            success: function(xml) {
                $(xml).find('members').each(function(){
                    var name = $(this).find("name").text()
                    alert(name);
                });
            }
        });
    });
</script>

No error but I get both names at the same time.

Like:

Bill GatesBob Barker <--first loop>

Instead of

Bill Gates <--first loop>

Bob Barker <--second loop>

Any help would be great!

Answer

fmgp picture fmgp · Apr 19, 2012

I think you iterate over members, not names:

success: function(xml) {
                $(xml).find('members').each(function(){
                    $(this).find("name").each(function(){
                        var name = $(this).text();
                        alert(name);
                    });
                });
            }

Or maybe your XML should looks like:

<members>
   <id>3422345</id>
   <name>Bill Gates</name>
</members>
<members>
   <id>232311</id>
   <name>Bob Barker</name>
</members>