简体   繁体   中英

Proper way to format user-entered text input for sending via JSON/AJAX to PHP?

I'm running into some problems with user-entered input that I want to send to PHP as JSON via AJAX that contains special characters, like ", ', etc. I'm sending the contents of an array (used for slickgrid), and everything works fine unless those characters are included. I know that PHP has the handy function mysql_real_escape_string, but is there any sort of jquery analogue? Here is the relevant code:

req = $.ajax({
 url: url,
 dataType: "text",
 data: {"data": $.JSON.encode(data)},
 type: "post",
 success: onSaveSuccess,
 error: onSaveError
});

Here's the PHP it is submitted to:

<?php
//$data = array();

//if (isset($_POST['data']))
//{
 //$data = json_decode($_POST['data']);
//}

//header('Content-Type: text/javascript');
//echo json_encode($data);
print_r($_POST);
?>

To be clearer, when special characters are included, neither the success nor error events are triggered.

I looked in firebug and it doesn't appear to send anything at all when the special characters are included... Of course, it does when it's just letters or something.

It was due to the script from here apparently failing on certain kinds of input. Switching to json2.js and using JSON.stringify has solved the problem.

data: {"data": $.JSON.encode(data)},

Passes up a more complex JSON object than you need.

$data = json_decode($_POST['data']);

Is looking for a serialized JSON object but jQuery is doing a lot of work for you in the background.

Try this

data: $.JSON.encode(data),

In your AJAX call. Then in PHP

$data['myPostValue'] = $_POST['myPostValue'];

You're sending a JSON object to the $.ajax call, and it is changing it into the name value pair that the server would normally get from a post.

javascript has an escape() function. you can $.JSON.encode(escape(data)) might work

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