Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX / Jquery XML parse

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!

like image 967
StealthRT Avatar asked Apr 19 '12 07:04

StealthRT


2 Answers

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>
like image 151
fmgp Avatar answered Oct 25 '22 22:10

fmgp


This way show names:

<script type="text/javascript">
$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "getMembers.php",
        cache: false,
        dataType: "xml",
        success: function(xml) {
            $(xml).find('name').each(function(){
                        var name = $(this).text();
                        alert(name);
            });
        }
    });
});

like image 34
Victor Cardenas Avatar answered Oct 25 '22 22:10

Victor Cardenas