I have the following javascript that sends data to a PHP function:
<script>
var mydata = {
id:123,
name: 'mike',
orders: []
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {save_data:mydata},
success: function(data) {
alert('php received: ' + data);
}
});
</script>
and my test.php file contains the following code:
<?php
if (isset($_POST['save_data'])) {
$json = json_encode($_POST['save_data']);
echo $json; // just to check what has been received
exit();
}
?>
What I expect to received from PHP is:
{"id":"123","name":"mike","orders":"[]"}
What I got back is {"id":"123","name":"mike"}
Notice that orders array has been eliminated from the output. No place holder for it. I tried adding some dummy elements in the array, and that worked fine, and I received the array back with the elements.
I need PHP to receive the json object as is, even if it contains empty arrays.
How can I do that?
The JSON object is created inside PHP. Before then you just have form data.
jQuery will encode form data in a PHP-friendly style.
If you give it:
data: { foo: [1, 2, 3] }
It will convert that to:
foo[]=1&foo[]=2&foo[]=3
(although it will percent encode the [])
You get a key=value pair for each value.
If you have an empty array then you don't have any values, so you don't get any key=value pairs.
There is no way to encode "an empty array" using PHP's extensions to the form url encoding syntax.
You have two basic options:
Tell PHP about what data structure you want to create in advance and have it fill in the empty arrays.
Generate the JSON on the client
It is not error of PHP. It cause by Jquery will igrone empty array when send it to server. So you have to parse array in 'orders' key to string JSON before send
var mydata = {
id:123,
name: 'mike',
orders: []
};
Change to
var mydata = {
id:123,
name: 'mike',
orders: JSON.stringify([])
};
Related
I am sending the array of dicts from javascript to python via a POST request that looks this way:
mydata.push({
department_id: department_id,
cardgroup_id: cardgroup,
doorgroup_id: doorgroup
});
$.post("data/save-office/"+office, {'data': JSON.stringify(mydata)}, function (data) {
console.log(data);
});
When extracting the payload in python:
departments = request.form.getlist('data')
The output is:
departments = ['[{"department_id":"1","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"2","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"3","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"4","cardgroup_id":"2","doorgroup_id":"2550"}]']
This displayed output is an array of one index and the inside is treated as a string rather than a dictionary.
How can I filter it or send it from javascript so that it can be decoded as an array of dicts not an array of strings?
Without changing your code, the simplest solution is using the json library's load or loads (load safe) method
import json
departments_string = request.form.getlist('data')[0]
departments = json.loads(departments_string)
print(departments)
[{'department_id': '1', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '2', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '3', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '4', 'cardgroup_id': '2', 'doorgroup_id': '2550'}]
I would further question using getlist, but we would need more deatils from you to deal with that.
I don t know why data formated as json using JSON.parse function return as Array type when I want to check the new converted type.
First I made ajax request to go and fetch data from a database as illustrated below
$.ajax({
url:'processBet.php',
data:'',
success:function(data){
//below I check the return data type
console.log( Object.getPrototypeOf(JSON.parse(data)));
//the return type is array.....why?
console.log((JSON.parse(data)); // to see the data
}
});
Obviously in the file that fetch data in the database will put data in Array.So before sending it I converted it in JSON using a php function json_encode as illustrated below
$ql = "SELECT * from tempdata" ;
$result=$pdo->query($ql);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($data = $result->fetch()){
$arrays[]=$data;
}
//Now I convert in json before sending
$json =json_encode($arrays);
echo $json; // the return data supposed to be json type
Below is the sample of the data return after succeessfull ajax request
So Iwould like to know why the return type is still array and not JSON since a new conversion has been made when the ajax request succeed
The reason is because how you are setting up your array before encoding it.
$arrays[] = $data;
PHP will set it as an object if the depth of the elements go beyond just an array of arrays.
Example:
If you create a simple 2d array like this one:
$p = [
'name' => 'jack',
'job' => 'ceo',
'age' => 'old'
]; // {"name":"jack","job":"ceo","age":"old"}
You will have an Object in your JS code; That's because of the way PHP handles it. However, look at this example as an alternative: This will return an array of objects:
$p = [[
'name' => 'jack',
'job' => 'ceo',
'age' => 'old'
],[
'name' => 'sam',
'job' => 'cool',
'age' => 'decent'
]];
echo json_encode($p); //[{"name":"jack","job":"ceo","age":"old"},{"name":"sam","job":"cool","age":"decent"}]
It's all about that key placement. If you have a key => pair array it will become an Object no matter what. Look at another example of a simple JS array:
print_r(json_encode([
'burger',
'pizza'
])); // ["burger","pizza"]
But if you add just one key=>pair to your array it will become an json object:
print_r(json_encode([
'burger',
'pizza',
'people' => [
'jack' ,
'sam',
'pete'
]
])); // {"0":"burger","1":"pizza","people":["jack","sam","pete"]}
Just for educational purpose if you throw it inside another 1d array you will get an array objects:
print_r(json_encode([[
'burger',
'pizza',
'people' => [
'jack' ,
'sam',
'pete'
]
]])); // [{"0":"burger","1":"pizza","people":["jack","sam","pete"]}]
Explanation:
When dealing with an array, it will strictly handle it's key from 0 to however many items are in the array; so an array in json_encode terms is anything with a simple 1d interface:
Which in PHP & JavaScript would look like this:
PHP
print_r([
'burger',
'pizza'
]); // Array ( [0] => burger [1] => pizza )
Javascript
console.log([
'burger',
'pizza'
]); // Array [ "burger", "pizza" ]
When adding the key to your array and making it into a 2d or more complex json_encode will convert it to a JavaScript Object; as we saw in the first example:
I would like to send multilevel JSON object as GET request parameter in JavaScript. To serialize I use this:
json_object = {
key_a: {
key_aa: 1,
key_ab: 2,
},
key_b: {
key_ba: 1,
key_bb: 2,
},
}
var encoded_json = jQuery.param( json_object );
and receive:
key_a%5Bkey_aa%5D=1&key_a%5Bkey_ab%5D=2&key_b%5Bkey_ba%5D=1&key_b%5Bkey_bb%5D=2
So, next, in python I would like to decode this string:
print(parse_qs(json))
and I receive:
{
'key_a[key_aa]': ['1'],
'key_a[key_ab]': ['2'],
'key_b[key_ba]': ['1'],
'key_b[key_bb]': ['2']
}
How can I transform this dictionary to form similar to input JSON object?
The answer of my question is: use JSON.stringify
serialized_object = JSON.stringify(object)
to serialize JavaScript object and next, use
json.loads(serialized_object)
in Python to get dictionary in case of POST request using.
i am editing content in an object saved in my AngularJs scope. Once submited i execute the following function:
$scope.saveQuestion = function(){
var request = $http({
method: "post",
url: "/manager/evaluations/evaluations/manage_questions/537c6179-8ed8-49b4-ac6b-25715f550349",
data: {EvaluationQuestion: $scope.newquestion}
});
}
$scope.newquestion has the following object:
[relevance: 3, evaluation_topic_id: 1, type: "text", action: "add", name: "asdfasdfsadfas"]
But the ajax request on the is just showing a Request Payload with:
Request Payloadview source
{EvaluationQuestion:[]}
EvaluationQuestion: []
Can any one guess why the sent data is empty?
It seems your $scope.newquestion is an Array, not an Object.
JSON doesn't support an Array data type with named keys in it. For example:
var foo = [];
foo['bar'] = 'One';
foo.baz = 'Two';
JSON.stringify(foo); // return "[]"
If the $scope.newquestion isn't required to be an Array, just use an Object.
Instead of
$scope.newquestion = [];
change it to:
$scope.newquestion = {};
I think you are using a wrong JSON syntax in $scope.newquestion.
Here you are defining an object which is supposed to be enclosed in {} but you are enclosing it in [] which stands for an array. I js arrays you cannot have [name1: value1, name2: value2].
Try replacing the square brackets with curely brackets, something like this:
{relevance: 3, evaluation_topic_id: 1, type: "text", action: "add", name: "asdfasdfsadfas"}
Hope that helps.
Try this:
data: {EvaluationQuestion: angular.toJson($scope.newquestion)}
I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});