views:

6011

answers:

4

I'm having a strange problem when retrieving JSON formatted text. I use jQuery post to send some data (also JSON formatted) to the server (running PHP) which works fine. Then, when I request the same data from the server using jQuery get, the callback method never executes. This only occurs when the data is JSON formatted and the data contains a line break. When I don't use JSON formatting it works fine. What baffles me is that there are no problems with uploading the data.

Uploading code: (works)

$.post("ajax/contents_ajax.php", {
    'title': caption,
    'text': frameText().getContent(),
    'image_id': img
},
//Callback

Download code: (doesn't work with line breaks)

$.get("ajax/contents_ajax.php", { 'get_item': id },
function (data){
    //Never gets executed if data contains line breaks
}
,'json');

The whole problem stems from the fact that the TinyMCE rich text editor seems to insist on inserting line breaks everywhere, even though I enabled the option

remove_linebreaks : true

I do prefer to have line breaks, but not if they break my code. Can anyone tell me what the problem is here, and perhaps how I can encode the linebreaks on the server with PHP?


Update

While the suggestions to replace '\n' with '' did not work, it was close to the right solution. This code removed the offending characters:

function parse($text){
    $parsedText = str_replace(chr(10), "", $text);
    return str_replace(chr(13), "", $parsedText);

}
A: 

do you get linebreaks like <br /> or newlines like \n? But try to replace them with PHP.

<?php
$string = 'asdfasf<br />asdfasf';
echo str_replace('<br />', '', $strin); // Replace <br /> with '' (nothing)
?>

or check out urlencode

Terw
I'm not sure, exactly. It just shows up as a new line in phpMyAdmin when I browse the database entry which stores the text, so there is no specific character representation I can see.
Morten Christiansen
+1  A: 

Like Terw but with replacing \n

<?php
 $json = str_replace('\n', '', $json);
?>

Should remove all line breaks, jquery shouldn't fail over
tags, but line breaks should not be in JSON.

Pim Jager
+2  A: 

Line breaks aren't the issue so much as they need to be properly escaped in JSON. If it's available to you, you can use json_encode which automatically escapes newlines. Failing that, you can use something like Pim Jager's method above, though a proper JSON encoder would be best.

xobofni
A: 

If you would like to keep the line breaks, you might try:

function parse($text) {
    // Damn pesky carriage returns...
    $text = str_replace("\r\n", "\n", $text);
    $text = str_replace("\r", "\n", $text);

    // JSON requires new line characters be escaped
    $text = str_replace("\n", "\\n", $text);
    return $text;
}
eyelidlessness