Chill Web Designs
Chill Web Designs

Reputation: 1331

Using jquery ajax to append content to a div id

I am using jquery ajax to get the names stored in an xml file and append it to a div id, but having some problems.

$(function(){

    $.ajax({type: "GET",
        url: "names.xml",
        dataType: "xml",
        cache: false,
        success: function(xml){ 

        $(xml).find('name').each(function(){ 

              $(this).text().append('#names');


        });

     }});

});

my xml file is formatted like so

        <?xml version="1.0"?>
    <item>
<name>Paul</name>
<name>John</name>
<name>Sam</name>
<name>Mitch</name>
etc.
</item>

and need to be appended to div id name.

<div id="names">

Paul
John
Sam
Mitch

</div>

Help

Upvotes: 2

Views: 7017

Answers (2)

Matt Ball
Matt Ball

Reputation: 360026

Try this:

$(function()
{
    var $names = $('#names');

    $.ajax(
    {
        type: "GET",
        url: "names.xml",
        dataType: "xml",
        cache: false,
        success: function(xml)
        {
            var combinedText = $(xml).find('name').map(function()
            { 
                return ' ' + $(this).text();
            }).get().join('');

            $names.text($names.text() + combinedText);
     }});
});

(non-ajax) Demo: http://jsfiddle.net/mattball/yGUCZ/

Upvotes: 1

James Allardice
James Allardice

Reputation: 166061

You are using append the wrong way round - the element to append to needs to come first:

$(xml).find('name').each(function() { 
    $("#name").append($(this).text());
});

Here is an example fiddle.

Upvotes: 3

Related Questions