1781 posts Time is what you desire most, but waste carelessly.
  • Has sold $250,000+ on Envato Market
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has been part of the Envato Community for over 5 years
  • Sells items exclusively on Envato Market
+5 more
Firsh says

I’m kinda stuck with this.. I have an array (object) which uses key / value pairs and I’d like to use it as data and send it to PHP as JSON . Got jquery.json-2.2.min.js this has the toJSON.

Array looks like: something[‘color’] = “red”

$.ajax({
                    type : 'POST',
                    url : 'handler.php',
                    dataType : 'json',
                    data: $.toJSON(something),

and the rest. PHP currently is just set up to return it..

$return = $_POST['color'];
echo json_encode($return);

Error handling reports textStatus: parsererror, errorThrown: Invalid JSON And the PHP says there is no such index as ‘color’.

I’ve been googling for hours and can’t get this one to work. Any help?

1698 posts Building the Web.
  • Has been a beta tester for an Envato feature
  • Sells items exclusively on Envato Market
  • Has sold $250,000+ on Envato Market
  • Had an item featured on Envato Market
+8 more
ZoomIt says
data: {color: something}
?
218 posts
  • Has been part of the Envato Community for over 4 years
  • Has referred 1+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 1+ items on Envato Market
+4 more
dilab says

Why do you send a json object to your backend php when you can just post it as {color:something}. And in your backend php, you can retrieve the value using $_POST[‘color’] ?

443 posts
  • Has been part of the Envato Community for over 5 years
  • Has sold $1,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
+1 more
SplitV says

As is mentioned above, you do not need the ‘toJson’ call. But I’m pretty sure your data parameter would not be ‘{color:something}’. It should be either ‘{color:something[‘color’]}’ OR if something only holds the data you wish to send to the server as key/value pairs then just set something as the data, “data: something”.

443 posts
  • Has been part of the Envato Community for over 5 years
  • Has sold $1,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
+1 more
SplitV says

But as your title suggests that you WANT to send a serialized json object, I will add that in order to do that you will still need a key/value pair as per the HTTP POST spec. So you will need to set your data parameter as something like ‘data : { json : $.toJSON(something)}’.

Also, to note, if you do send the serialized json object you will not be able to access the attributes like ’$_POST[‘color’]’. You would need to unserialize the data from ’$_POST[‘json’]’(or whatever key you use) and then retrieve ‘color’ from that unserialized json object.

1781 posts Time is what you desire most, but waste carelessly.
  • Has sold $250,000+ on Envato Market
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has been part of the Envato Community for over 5 years
  • Sells items exclusively on Envato Market
+5 more
Firsh says

SplitV that seemed logical. It even works if I pick JS out of the process.. This works (php):

$json = '{"json": {"color" : "red"}}';
$props = json_decode($json, true);
$return['msg'] = $props["json"]["color"];
echo json_encode($return);

“red” is the value of “msg” this way.

But if I get the JSON serialized string from JS (which I assume is the same as I hardcoded in the previous example: JS:
data : { "json" : $.toJSON(something)},
PHP :
$props = json_decode($_POST['json'], true);
$return['msg'] = $props["json"]["color"];
echo json_encode($return);

The value of “msg” in the return is just “null” (invalid JSON , right?) Isn’t this { “json” : $.toJSON(something)} producing {“json”: {“color” : “red”}}?

3303 posts
  • Provided great contribution to our forums
  • Nominated Community Superstar of the month
  • Helps us moderate the forums
  • Has been part of the Envato Community for over 5 years
+18 more
dtbaker Moderator says

Best to post a link to the example, so someone here can use firebug to see what data is actually getting posted to the server. That’s prolly where the issue is.

Maybe try to simplify your code, don’t use the toJSON stuff.

var something = {
  'color': 'red',
  'size: 'big'
};
// jQuery ajax post data to php script http://api.jquery.com/jQuery.ajax/
$.ajax({
 type : 'POST',
 url : 'handler.php',
 dataType : 'text', // use text for debugging, then swap to json when you have php correct.
 data: something,
 success: function(res){
   // res will be a 'text' result from the php script. simply alert it so we can debug.
   alert(res);
 }
});

now the php script handler.php:

// we've POST'ed the  javascript "something" object to this php script.
// echo it straight back so we can see it working in our js alert();
echo "Post data: \n" . var_export($_POST,true) . "\n";
// start a php array which we will return as ajax to our javascript (eventually)
$return = array();
$return['foo'] = $_POST['color']; // grab value from js post.
echo "Now the json encoded result: \n";
echo json_encode($return);

note: haven’t tested and had a few beers so most likely wont work :P

443 posts
  • Has been part of the Envato Community for over 5 years
  • Has sold $1,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
+1 more
SplitV says

Your problem lies in this line…

$return['msg'] = $props["json"]["color"];

It should just be…

$return['msg'] = $props["color"];

The serialized json object is the serialized object you created from ‘something’. The key ‘json’ is just the key you made for use in the HTTP POST so it would be non-existent in the unserialized object/array.

1781 posts Time is what you desire most, but waste carelessly.
  • Has sold $250,000+ on Envato Market
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has been part of the Envato Community for over 5 years
  • Sells items exclusively on Envato Market
+5 more
Firsh says

Thanks for the replies these cleared some thing about this whole process. However I’m now sending these values manually, I mean I’m not just passing the object, but as key value pairs (I write them out) and I request the value by hand..

701 posts
  • Has been part of the Envato Community for over 6 years
  • Has referred 1+ members
  • Located in Canada
  • Has collected more than 1000 items on Envato Market
chrismccoy says

i have a piece of code i used with wordpress it may help

http://codejab.com/code/v/loading-posts-with-ajax.html

Helpful Information

  • Please read our community guidelines. Self promotion and discussion of piracy is not allowed.
  • Open a support ticket if you would like specific help with your account, deposits or purchases.
  • Item Support by authors is optional and may vary. Please see the Support tab on each item page.

Most of all, enjoy your time here. Thank you for being a valued Envato community member.

Post Reply

Format your entry with some basic HTML. Read the Full Details, or here is a refresher:

<strong></strong> to make things bold
<em></em> to emphasize
<ul><li> or <ol><li> to make lists
<h3> or <h4> to make headings
<pre></pre> for code blocks
<code></code> for a few words of code
<a></a> for links
<img> to paste in an image (it'll need to be hosted somewhere else though)
<blockquote></blockquote> to quote somebody

:grin: :shocked: :cry: Complete List of Smiley Codes

by
by
by
by
by
by