Question

I'm currently requesting some text via jQuery on a php page. The problem is that the new line symbols \n are displayed in the alert window, and do not get interpreted as new line. I do not escape the string at any time.
In the error: function(..) block of my jQuery request, I get the string returned by php via jqXHR.responseText, here is it's exact value :

Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n

When I do this, new lines DON'T WORK :

alert(jqXHR.responseText);

So to debug, I decided to paste the php response string (which is the previous string) directly in the alert() function, and in this case the new lines WORK :

 alert("Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n)");

The string is exactly the same, but yet new lines don't work when I use jqXHR to get it. Anybody has any clue ?

EDIT: php code that generates the string :

$errorMessage = 'Some fields are empty!' . '\n'
              . '$name= '               . $name . '\n'
              . '$schedule= '           . $schedule . '\n'
              . '$free_connection= '    . $free_connection . '\n'
              . '$free_coffee= '        . $free_coffee . '\n'
              . '$rating= '             . $rating . '\n'
              . '$lat= '                . $lat . '\n'
              . '$lng= '                . $lng . '\n';
echo $errorMessage;
Was it helpful?

Solution

You're using the wrong type of quotes. In PHP, escape sequences aren't processed in single quotes, only in double quotes. So it should be:

$errorMessage = 'Some fields are empty!' . "\n"
              . '$name= '               . $name . "\n"
              . '$schedule= '           . $schedule . "\n"
              . '$free_connection= '    . $free_connection . "\n"
              . '$free_coffee= '        . $free_coffee . "\n"
              . '$rating= '             . $rating . "\n"
              . '$lat= '                . $lat . "\n"
              . '$lng= '                . $lng . "\n";
echo $errorMessage;

OTHER TIPS

I do not know if I understood well but You can try

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

or

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });

  $( "<ul/>", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top