1

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?

3
  • It's not very clear what you want to do Commented Dec 5, 2010 at 19:52
  • Have you set the datatype as 'json' ? dataType: 'json' Commented 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. Commented Dec 5, 2010 at 20:12

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

All you have to do is put quotes around the string

data: { 'data': '{"name":"chris"}' }

Comments

0

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.