tags:

views:

36

answers:

1

Hi, I have a bit of a problem.

I have an ajax request that is sent out to do a database update. A response is then returned that looks like:

...
...
</head>
<body class="contentpane">
{"id":"27","votes":14,"sum":45,"avg":"3.2"}
</body>
</html>

How can I get the contents of body class "contentpane" and then convert this to a JSON object?

My request function looks like this:

  jQuery.post("index.php?option=com_ttvideo&task=savevote&tmpl=component", {rate: value, id: <?php echo $this->video->id; ?> }, function(html)
  {
    // get contents of "contentpane" from response html
    // convert to JSON object e.g.
    // var rating = jQuery.parseJSON(content_of_body);    
    // is the above JSON parse correct?    

    // Select stars to match "Average" value
    ui.select(Math.round(rating.avg));

    // Update other text controls...
    jQuery("#avg").text(rating.avg);
    jQuery("#votes").text(rating.votes);

    // Show Stars
    jQuery("#loader").hide();
    jQuery("#rat").show();

  });
A: 

Like this:

$.parseJSON($('body', html).text())

I'm assuming, perhaps incorrectly, that the JSON will be HTML escaped. If it isn't, you will sometimes be able to call .html() instead of .text(), but will more likely need to write your own parser.

You should replace your webservice with a real JSON response.

SLaks
This is a component I am developing in Joomla and to keep the php functions within the Joomla framework it requires to run the response through the component MVC framework - draw back of this is that it returns all that html as well, tut tut :(
Martin
I'm trying to work through this 1 step at a time, 1. getting the value out of the body tag using var rating = jQuery("body", html).text(); but this returns blank, replacing with .html() returns null.
Martin
@Martin: I can't imagine that there is no way around that. However, I don't know Joomla. Ask a separate question here.
SLaks
Try `$(html).find('body').text()`.
SLaks
Thanks but I found this article about JSON responses for MVC in Joomla - http://docs.joomla.org/Handling_the_server_side_of_Ajax_requests
Martin
Martin