Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem when retrieving text in JSON format containing line breaks with jQuery

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);  } 
like image 864
Morten Christiansen Avatar asked Dec 27 '08 20:12

Morten Christiansen


People also ask

Are line breaks allowed in JSON?

JSON does not allow real line-breaks. You need to replace all the line breaks with \n .

How does JSON handle line breaks?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.

How do I fix JSON format?

JSON Syntax RulesData is in name/value pairs. Data is separated by commas. Curly braces hold objects. Square brackets hold arrays.

Does formatting matter in JSON?

Show activity on this post. JSON is a serialization format, not a presentation format. As such, there is no "standard" indentation - JSON is typically sent as compactly as possible. I see.


1 Answers

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; } 
like image 183
eyelidlessness Avatar answered Sep 28 '22 16:09

eyelidlessness