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?
2 Answers 2
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/
3 Comments
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 serverPOST . If want GET can simply change the object I have in data with the string "action=update"..See docschange $('#history').text( data ); to $('#history').html( data );
$output = $output . '<p>';concatenate with$output .= '<p>';and define$outputabove your while loop