Question

I am taking user input sending it to server using jQuery ajax...after inserting user values in database I am sending response back to client as JSON string as following

echo '{"success":"true","data":"'.nl2br($a).'","type":"text"}';

as user input can contain new line, I am using nl2br so that all new line characters are converted to <br> and also know that JSON doesnt support multi line, thats why I am using nl2br....but parsing is failing at client side

pls tell me what the reason and how can I solve it?

parsing code var obj = jQuery.parseJSON(data);

Était-ce utile?

La solution

You should be using json_encode, wich will generate a JSON string that contains \r\n for line breaks. Then you will have to replace each \r\n occurences by <br> tags.

echo str_replace('\r\n','<br>', json_encode(array("success"=>"true","data"=>$a,"type"=>"text")));

Autres conseils

echo json_encode(array("success"=>"true","data"=>$a,"type"=>"text")

Use the php function json_encode rather then trying to set the encoding yourself. You'll save yourself a lot of trouble that way. http://php.net/manual/en/function.json-encode.php

nl2br() does not replace the line breaks, only inserts <br> before them.

As such, \n is being returned and therefore creating invalid JSON.

You should use json_encode() when creating JSON strings. For simplicity, you could simply use it on data:

echo '{"success":"true","data":' . json_encode(nl2br($a)) . ',"type":"text"}';
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top