Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are new lines not working in this javascript alert window?

I see quite a few different issues with the alert window and new lines. Most are that the \n is considered a new line in PHP rather than getting sent to javascript.

In my case, the string is being outputted in a new window showing \n. I just tried actually writing \n into an alert box via jsfiddle, and that worked, so it must be my method of doing things...

Here is the string returned to console. as you can see, the \n is definitely there:

Username is required\nPassword is required\nEmail is required\nPhone is required\nCardnumber is required

However, it shows up like this:

An alert with \n instead of a new line

Why is this happening? I think it may have something to do with the data type, as it is returned from $.ajax

if (canAjax && !try_ajax) { 
    e.preventDefault();
    $.ajax({
        type: "POST", 
        url: "mobilesubmit.php",
        data: {"use_ajax": true, "formdata": $("#register_form").first().serializeArray()},
        success: function(data) {

            // This stupid thing should make new lines!
            alert(data);

            console.log(data);
        },
        error: function (request, status, error) {
            try_ajax = true;
            $("#register_form").submit();
        }
    });
}
like image 810
Radley Sustaire Avatar asked Jan 23 '12 05:01

Radley Sustaire


3 Answers

The most likely cause of this is that your PHP code is escaping the backslash by adding another backslash in front of it. By the time it gets to your JS code, it's actually

"Username is required\\nPassword is required..."

You can inspect the raw response in the network panel of your debugger. If you try to view it in the console, it'll display the formatted output instead of the raw output.

Double-check your method of JSON serialization in your PHP code and make sure it's doing what you expect with the \n.

like image 66
Amit Avatar answered Oct 06 '22 21:10

Amit


If your console log is showing \n rather than a new line, then it means the \ is escaped in the original string...

Compare

console.log(1,"\\n\\n");
console.log(2,"\n\n");

Solution

use .replace() to swap your \n with newline characters

console.log(3,"\\n\\n".replace(/\\n/g,"\n"))
like image 42
Billy Moon Avatar answered Oct 06 '22 22:10

Billy Moon


try adding a space after \n .It should work

like image 1
Ajeet Sinha Avatar answered Oct 06 '22 20:10

Ajeet Sinha