JSON appearing as PHP array without using json_decode() - php

I'm using jstree on a project and attempting to save my tree to a database.
I'm obtaining the tree data as follows:
var tmp = $('#tree').jstree(true).get_json();
console.log(tmp);
This produces a JSON object in the console as I'd expect:
However when I post this to a PHP script using jquery...
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});
... It is showing a PHP array of my data:
The script which I have at /saveTree displays the POST data in the tree array post key:
var_dump($this->request->data['tree']);
I assumed since the data I'm posting to the script is in JSON format I'd need to json_decode() it at the other end? If not, why not?
I've also tried adding dataType: 'json', in the ajax request but that makes no difference.
What's happening here?
Please note the PHP script at /saveTree is running in CakePHP 2.x so the line of PHP above is equivalent to var_dump($_POST['tree']) in regular PHP.

If you want send the data as string you can JSON.stringify(tmp);
tmp = JSON.stringify(tmp);
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});

Related

Passing JSON object from ajax to PHP script

I am currently trying to pass a json object from ajax to php. But it does not get me anything..Below is my code. I already tried print_r[$_POST] it just returns Array(). What's wrong with this code?
This is my code: screenshot of my code
If ajax is sent with "GET" instead of "POST", you should use $ _GET in your code.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Are you sure that the Type parameter is post?
or use
print_r($_GET);

Javascript sending array with files to php

So i'm sending a jquery object that contains some info about a file and the actual $("#input").files[0]; item.
The jquery/javascript looks something like the following:
$.ajax({
url: '/upload/create',
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
success: function(msg) {
alert(msg);
}
});
The data variable is a JQuery object that contains info about the uploaded file and the file itself(I think), I just passed it in the object.
Is there any way to extract and save this file on the server-side with PHP?
Just remove the JSON.stringify() call and you should be good. data should be an object, which gets converted to PHP's associative $_POST or $_GET array, stringify converts it to a string.
data: data,

Ajax post returning empty $_POST

Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.
Here is my js:
$.ajax({
type: "POST",
url: "/account/book-promo.php",
data: '{"firstName":"Peter" , "lastName":"Jones"}',
success: function(response) {
console.log(response);
}
});
And my PHP:
<?php
var_dump($_POST);
exit;
Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:
array(0) {
}
The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!
Any and all suggestions welcome!
send it like if you want to send it as json.
data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },
and if you want to send it as POST just remove quotes '
data: {"firstName":"Peter" , "lastName":"Jones"},
You have to do this:
$.ajax({
type: "POST",
dataType: "json", // <---------------its required if response is json
url: "/account/book-promo.php",
data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
success: function(response) {
console.log(response);
}
});
You said in your post retuning the JSON from my PHP:
so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.

javascript array to php array

i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.

JS Ajax calling PHP and getting ajax call data

I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)

Categories