0

I am using this bit of PHP to return a chunk of html:

if ($action = "update")
 {
 connect_db();
 $query = mysql_query("SELECT * FROM convo ORDER BY date ASC") or die (mysql_error());
 while($row = mysql_fetch_array($query))
 {
 $output = $output . '<p>';
 $output = $output . '<b>From:</b> ' .$row['from'];
 $output = $output . ' <b>To:</b> ' .$row['to'];
 $output = $output . ' <b>Message:</b> ' .$row['content'];
 $output = $output . "<br />";
 $output = $output . '</p>';
 }
 //htmlentities($output);
 header('Content-Type: application/json');
 echo json_encode( $output );
 }

And then insert it into a <div> with this bit of jQuery:

function update(){
 $.ajax({
 type: "GET",
 url: "actions.php",
 data: { 
 'action': 'update'
 },
 dataType: "json",
 success: function(data)
 {
 console.log('update called');
 console.log( data);
 $('#history').text( data );
 //$('#status').text('sent!');
 }
 }); 
 setTimeout(update, 5000);
 } 

The ajax call works and returns the correct html however when inserted it is not formatted, I can see all the html code in the browser. See example picture: browersoutput

Should be using something other than .text?

asked Jan 7, 2013 at 3:30
1
  • 1
    Dont use $output = $output . '<p>'; concatenate with $output .= '<p>'; and define $output above your while loop Commented Jan 7, 2013 at 3:33

2 Answers 2

1

You are creating JSON in php, and using json dataType for no reason when you want html.

Just output the html string in php and remove the dataType:'json from AJAX.

echo $output ;

Then instert using html() method

 $('#history').html( data );

The load() method is ideal for your case. It is a $.ajax shortcut method. You could replace all the AJAX you have with:

 $('#history').load("actions.php", { 'action': 'update'},function(){
 console.log('new content inserted now')
 })

API reference: http://api.jquery.com/load/

answered Jan 7, 2013 at 3:35
Sign up to request clarification or add additional context in comments.

3 Comments

That's fancy. Do I still need to return the data from my php page with json_encode() or does it just take the straight html?
load is strictly for html. It will replace the current content of the selector with html from server
oh will be a POST . If want GET can simply change the object I have in data with the string "action=update"..See docs
1

change $('#history').text( data ); to $('#history').html( data );

answered Jan 7, 2013 at 3:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.