views:

188

answers:

1

I scratch my head in frustration, but I can't find the answer. I'm new to Ajax and I'm trying this easy script:

Here's my code:

JAVASCRIPT:

$(document).ready(function(){    
 $("#toggle_album").click(function () {  
  $.post('backend/load_album_thumbnails.php', {  
      text: 'my string',  
          number: 23  
  }, function(xml) {  
          var timestamp = $(xml).find("time").text();
          alert(xml);
          alert(timestamp);
  });  
 });
});

the alert(xml) returns:

     <? xml version="1.0"?>
<response status="ok">
<time>23:33:13</time>
<string>my string</string>
</response>

the alert(timestamp) returns empty

i have also tried:

timestamp = $("time",xml).text();

with the same result.

I added the extra space in the xml start tag because it dissapeared here on stackoverflow. The only reason for this error I can think of is that the return data isn't in XML format, but I can't figure out why that would be the case.

Appreciate any answers.

+1  A: 

You're correct, the reason it's not working is that the return data isn't in XML format. Generally, if a web server doesn't return a text/xml Content-Type header, then certain browsers (and therefore jQuery) won't bother parsing the XML.

To get it to work, your options are:

  1. Modify your response headers to specify XML format using PHP's header() function and then, change your response so that it uses well-formed XML. The code to do this would look something like:

    header('Content-Type: text/xml; charset=UTF-8');
    echo "<?xml version=\"1.0\"?>
    <response status="ok">
      <time>$timestamp</time>
      <string>$mystring</string>
    </response>";
    
  2. Change the way you handle the response in your JavaScript code (for example, write a simple regular expression parser, although this is considered bad for your health)

  3. Change your response to something like JSON so that you can use jQuery's $.getJSON() method to send the request and parse the response to a JavaScript object (PHP has some very nice built-in JSON functions).
Horatio Alderaan
I'd suggest to move to JSON too, it's easier to encode an parse.
Patonza
1). Will try soon!2). LOL!3). Yeah I considered JSON but the script will eventually return a whole bunch of image information, which makes the XML-format ideal.
Mattis