1

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);

vikas devde
  • 11,691
  • 10
  • 35
  • 42

3 Answers3

1
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

AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
  • 1
    I am getting this string as response `{"success":"true","data":"dada\r\ndada\r\nada","type":"text"}` i think here I need to replace all \r\n to
    ....??
    – vikas devde Apr 01 '13 at 19:29
1

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"}';
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

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")));
plalx
  • 42,889
  • 6
  • 74
  • 90