I'm trying to write a jQuery function to send a query string to a PHP script, but I can't seem to get the text to get to the server in the correct format. I want to send this query string (with the appropriate URL encoding):
data={"name":"Chris"}
where 'data' is always a JSON string. Using jQuery's .ajax
function I tried setting my data variable to
data: { 'data': {"name":"chris"} },
but PHP ends up getting:
data[name]=chris
What's the proper way to send the data back to the server so that the JSON string is properly reserved, without having to hand-craft the string?
-
It's not very clear what you want to doHarmen– Harmen2010年12月05日 19:52:35 +00:00Commented Dec 5, 2010 at 19:52
-
Have you set the datatype as 'json' ? dataType: 'json'Elliott– Elliott2010年12月05日 20:00:15 +00:00Commented Dec 5, 2010 at 20:00
-
dataType is for the data coming from the server. I'm trying to send JSON data to the server.dragonmantank– dragonmantank2010年12月05日 20:12:03 +00:00Commented Dec 5, 2010 at 20:12
4 Answers 4
First, you'll need to use json2.js because jQuery does not include the capability to output JSON, only to parse it, and the method we will be using is not supported in IE 6/7. Convert your JavaScript object to JSON:
var encoded = JSON.stringify(data);
Then you need to include that JSON-formatted string as request data:
$.getJSON(url, {data: encoded}, function() { ... });
Edit: An older version of this post referred to the jquery-json plugin, but it's obvious that that plug-in was written when jQuery 1.3.x was current.
Comments
All you have to do is put quotes around the string
data: { 'data': '{"name":"chris"}' }
Comments
Although, unclear from your question, if you are trying to know how to handle JSON strings properly in PHP, the best way would be to use the functions json_encode
and json_decode
.
Comments
This is wrong:
data: { 'data': {"name":"chris"} },
You get a indexed array with key of name and value of chris.
this is right:
{ name : "chris" }
If you want in php:
name = "chris";
Then you must send
{ name : "chris" }
Depending on if you GET you can get:
$name = $_GET["name"];
echo $name; // chris