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?

Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
asked Dec 5, 2010 at 19:38
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.

answered Dec 5, 2010 at 20:00

Comments

1

All you have to do is put quotes around the string

data: { 'data': '{"name":"chris"}' }
answered Dec 5, 2010 at 20:08

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.

answered Dec 5, 2010 at 19:56

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
answered Apr 10, 2012 at 18:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.