Tool
Tool

Reputation: 12488

jquery not working with xml

I'm having problems using xml with jquery.

This is the xml produced on the page: (firebug copy pasted)

<?xml version="1.0" encoding="utf-8" ?>
<product cookie="The red">
  <timediff>01:09:46</timediff>
  <username>denis</username>
  <price>25</price>
</product>

<product cookie="The red">
  <timediff>01:09:46</timediff>
  <username>denis</username>
  <price>35</price>
</product>

On body load, proper function is called.

The jquery code is here:

    $(document).ready(function() {


             $.ajax({
                type: "GET",
                url: "ajax",
                dataType: "xml",
                success: parseXml
             });

    });


}

function parseXml(xml)
{
      $("#timer2").html("Hey there");
      $(xml).find("product").each(function()
      {
           $("#timer2").html("Hey there");
      });
}

Nothing in parseXml function is working. I think it gets called but it can't find #timer2 (perhaps it's because xml is outputed through a php file?). I have the div id="timer" in body.

Edit: not sure if it's important, but the url "ajax" is a route (using a framework) that leads to this file:

ajaxSuccess.php

<?php
    echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    //time, username, price, id (so jquery can know what to change)

    foreach($acs as $auction) {

        echo "\n<product", " cookie=\"The red\">\n";
        echo "  <timediff>", $auction['time'], "</timediff>\n";
        echo "  <username>", $auction['username'], "</username>\n";
        echo "  <price>", $auction['price'], "</price>\n";
        echo "</product>\n";


    }
?>

Upvotes: 0

Views: 95

Answers (2)

Ben
Ben

Reputation: 7597

You need to supply the relevant bits of the page mark-up for anyone to troubleshoot this fully. You also need a valid XML file: there's no root element in there, you just go straight into your two product nodes.

If parseXml can't find the element with the id timer2 then obviously it's dead in the water—the php file which supplies your XML shouldn't affect this in any way that I can see.

I'm a little confused by your last statement. You say you have a div in your page with the id timer, but I don't see how that's relevant: it's timer2 that you're trying to manipulate in this snippet. Or am I missing something here?

Upvotes: 1

Erlock
Erlock

Reputation: 1968

Your XML is malformed and can't be parsed: a XML document must have only one document Element. Nest your product elements into another element:

<products>
<product cookie="The red">
  <timediff>01:09:46</timediff>
  <username>denis</username>
  <price>25</price>
</product>

<product cookie="The red">
  <timediff>01:09:46</timediff>
  <username>denis</username>
  <price>35</price>
</product>
</products>

Upvotes: 1

Related Questions