简体   繁体   中英

JQuery success results in \r\n characters

I have these characters in my results.
The same code works fine on another page.

This is my PHP:

// Insert Data $queryData = $db->prepare("INSERT INTO tbl_Category ( Status , Parent , Name ) VALUES (?, ?, ?)");

$insertData = $queryData->execute (
    array (
        $Status,
        $Parent,
        $Name,
    )
);

if(insertData) { echo "success"; } else { echo "error"; }

This is my JQuery:

$.ajax({
    type:'POST',
    url:"ajax/Category.php?ajaxPost=newCategory",
    data:$('form#frmAction').serialize(),
    success: function(result){
        if(result == "success")
        {
            alert("ok ");
        }
        else if(result == "error")
        {

        alert("püff");
        }
    }
});

This is what the Firefox Debugger shows

And my result is:

result = "success\r\n" 

\\r\\n refer to the end of the string characters. Interacting between JavaScript and PHP using ajax is usually implemented using json , which is a data format supported widely by all programming languages.

You may refactor your code as follows. The die() function is used to ensure no extra output is printed by the PHP script, since this would result in invalid json syntax.

category.php

if($insertData) { 
    die(json_encode(['result' => true])); 
} else { 
    die(json_encode(['result' => false, 'errorMessage' => 'Optional error message goes here.'])); 
}

jQuery

Note: I have used the $.post() function, this is a shorthand for $.ajax(type: 'POST') .

$.post('ajax/Category.php?ajaxPost=newCategory', $('form#frmAction').serialize(), function(r) {
    if(r.result) {
        alert("OK");
    } else {
        alert("Something went wrong: " + r.errorMessage);
    }
}, 'json');

You can use .trim() to remove unwanted \\r\\n:

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

 var result = "success\\r\\n".trim(); if (result == "success") console.log("ok "); else console.log("not ok "); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM