ajsie
ajsie

Reputation: 79786

return json string with html characters?

i want to call a php with jquery ajax to perform some database things and then return 2 lists of links. so i have to pass these two link lists back to jquery so it can display list 1 in the left side of the webpage and list 2 in the right side.

i created the lists in separate arrays that i send back to jquery with json_encode but i noticed that it escapes all the html characters.

<a>dog</a> became <a>dog<\/a>

so when i displayed the list in the html they werent links anymore.

how can i preserve the html codes in my returned arrays to jquery?

EDIT: is this the right way to go if you want to split up data from php so that jquery can display them in different locations in html?

// list 1
while($row = mysqli_fetch_assoc($saved_tags))
{
    $display_saved_tags[] = "<a id='showtag' href='answer.php?id=" . $row['id'] . "'>" . $row['name'] . "</a><br />";
}

// list 2
while($row = mysqli_fetch_assoc($related_tags))
{
    $display_related_tags[] = "<a id='showtag' href='answer.php?id=" . $row['id'] . "'>" . $row['name'] . "</a><br />";
}

// return lists to jquery
echo json_encode('display_saved_tags' => $display_saved_tags, 'display_related_tags' => $display_related_tags));

Upvotes: 0

Views: 7396

Answers (2)

Corey Ballou
Corey Ballou

Reputation: 43507

json_encode's escape characters directly conflict with HTML output. I have had the same issue but decided to use an alternative solution at the time. I just had a thought that you could perhaps do this:

$data = new stdClass();
$data->html1 = base64_encode('<h1>html in here</h1>');
$data->html2 = base64_encode('<p><strong>more html</strong></p>');
echo json_encode($data);

On the frontend:

callbackFunction(json) {
    alert(base64_decode(json.html1));
    alert(base64_decode(json.html2));
}

You would need the javascript implementations of base64_decode and utf8_decode which can be found at: http://phpjs.org/functions/base64_decode:357

Upvotes: 6

Sarfraz
Sarfraz

Reputation: 382806

use can use below function to un-escape the chars when reading or sending on to the browser:

 html_entity_decode('your response here');

Also because your are using json_encode, make sure that you don't need the below function in your code:

json_decode

Upvotes: 0

Related Questions