Can't pass multidimentional array to php with ajax - php

Array I am trying to pass:
var params = [];
params['request'] = "movies";
params['param'] = [];
params['param']['sortBy'] = "title";
params['param']['sortOrder'] = "asc";
Ajax call:
return $.ajax({
type: "POST",
url: "http://192.168.0.100:83/getData.php",
cache:false,
data: params,
dataType:"json",
success: function(data){
if(data != null){
console.log(data);
}
Problem is that the php script only receives $_POST['request'], params is non-existent.
If I view params array in the console log before the ajax call I see this:
[request: "movies", param: Array[0]]
length: 0
param: Array[0]
length: 0
sortBy: "title"
sortOrder: "asc"
__proto__: Array[0]
request: "movies"
__proto__: Array[0]
It seems like the problem could be that "param" parameter is not passed because it is seen as empty (it is not, at least before it is passed to ajax call), but why this is happening I have no idea. What am I missing here?

You have declared params as an array [] but assigned object properties to it using the ["string"] notation. This resulted in empty arrays with additional properties appended to the Array object.
Instead, it should have been declared as an object literal, with another object literal nested inside.
var params = {
request: "movies",
param: {
sortBy: "title",
sortOrder: "asc"
}
};
The structure of the $_POST should be something like:
Array
(
[request] => movies
[param] => Array
(
[sortBy] => title
[sortOrder] => asc
)
)

You could send the data as JSON and decode it in php using json_decode():
$.ajax({
data: { paramData: JSON.stringify( params),
/* other ajax options*/
})
Then in php receive it with:
$params= json_decode($_POST['paramData']);
echo $params['request']; /* should return "movies" as response*/
Include json2.js library for older browsers that don't support JSON methods
EDIT: after a little testing will definitely need to change params to object and params.param to object, Changing [] to {} will accomplish this:
var params = {};
params['request'] = "movies";
params['param'] = {};
params['param']['sortBy'] = "title";
params['param']['sortOrder'] = "asc";
DEMO: http://jsfiddle.net/germk/2/

Related

Array values returns null

I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request
$(function() {
$("#del").click(function() {
var file_id = 32
var file_update = 1321321
var obj = {
file_id: file_id,
file_update: file_update
};
$.ajax({
type: "post",
url: "config/ajax.php",
data: {
"file_update": JSON.stringify(obj)
},
success: function(response) {
alert(response);
}
})
})
})
Here is my php code
if (isset($_POST["file_update"])) {
$file_update = json_decode($_POST["file_update"], true);
$x = $file_update[0];
var_dump($x);
var_dump($file_update);
}
The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.
$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.
If you want to access specific array values use:
$file_update['file_id'];
$file_update['file_update'];
If you want to access the first element of an associative array you can use the following:
$key = array_keys($file_update)[0];
$value = $file_update[$key];

Can't print the json from ajax post using json_decode

I am using ajax to post data to a php script for work to be done... Basically, I'm taking all the form variabes, and creating json... Then taking this json and sending it to the controller script:
function createJSON() {
jsonObj = [];
$("input[class=form-control]").each(function() {
var id = $(this).attr("id");
var value = $(this).val();
item = {}
item [id] = value;
jsonObj.push(item);
});
jsonData = JSON.stringify(jsonObj);
var request = $.ajax({
url: "../../../../ajax/signupController.php",
type: "POST",
data: jsonData,
dataType: "html"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
My code gets to the php script fine, and when I use "print_r" in php to print the output, I get this:
Array
(
[0] => stdClass Object
(
[mail-firstname] => FName
)
[1] => stdClass Object
(
[mail-lastname] => Lname
)
)
My problem is, I can't GET AT the elements... I have tried:
$data = json_decode(file_get_contents('php://input'));
foreach ($data as $key => $value) {
print "<p>$key | $value</p>";
}
but I can't get at the array elements... I get an error... What am I missing about accessing the array after decoding the file contents?
Thanks.
Update:
Modified foreach:
foreach($data as $key=>$value){
print $value->ccyear;//now I can get at individual elements
}
BUT ANY VALUE THAT HAS A DASH IS CAUSING THE SCRIPT TO FAIL... For example, if the name is "mail-firstname" PHP thinks it's mail AND firstname...
The problem is that your values are nested an extra level in your data. And they each have different keys, so it's hard to get at them. It would be better if you use the id as the keys of the top-level array, rather than nesting them:
jsonObj = {};
$("input[class=form-control]").each(function() {
var id = this.id
var value = this.value;
jsonObj[id] = value;
});
Then you should change your PHP to use the second argument to json_decode(), so you get an associative array instead of a stdClass object:
$data = json_decode(file_get_contents('php://input', true));
I'm not really sure why you need to send JSON. Why not just use:
data: jsonObj;
Then you can access the inputs as $_POST['mail-firstname'], etc.

How to create a two-dimensional array in PHP and iterate through it with Javascript

Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});

json array to php

I have array in json, but I want to print it in php. I get in post this :
[{"cartData":{"id":"dragged_567737","left":"255px","top":"71px"}},{"cartData":{"id":"dragged_757836","left":"43px","top":"73px"}}]
but when I use print_r($_POST) in my php file, it print me the empty array.
there is my js code:
jQuery('#save_project_data').click( function() {
var array=[];
var numItems = $('.icart').length;
$(".icart").each(function(index) {
var cart_id = $(this).attr("id");
var cart_left = $(this).css("left");
var cart_top = $(this).css("top");
var cartData = {
"id" : cart_id,
"left" : cart_left,
"top" : cart_top
};
queryStr = { "cartData" : cartData };
array.push(queryStr);
});
var postData = JSON.stringify(array);
$.ajax({
url : "modules/cart_projects/saveData.php",
type : "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data : postData,//{ 'data': '{"name":"chris"}' }
traditional: true,
success: function(){
alert("OK");
}
});
return false;
});
PHP has native support for decoding JSON with json_decode();
$data = json_decode($_POST['myJson']);
print_r($data);
The PHP $_POST array is interpreted from key value pairs, so you need to change your ajax call like below, because your code is sending the post data with no key.
data : { myJson : postData },//{ 'data': '{"name":"chris"}' }
If you change the data structure like above, you need to also remove your application/json; charset=utf-8 content type.
From the Manual:
Takes a JSON encoded string and converts it into a PHP variable.
If you're sending raw JSON-strings to PHP, $_POST will not be populated (as it needs a standard urlencoded string as submitted by POST requests to decode). You can solve this by either using postData as an object: {'json': json}, so that you get the value in $_POST['json'], or by reading the raw response:
$json_string = file_get_contents('php://input');
$struct = json_decode($json_string, true);
Try to use json_decode() function.
According to jQuery.ajax() documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
To be safe, you might be better off using the jQuery.post() method.
Finally, I suggest to give the data property an object. That way you can set an identifier for your post data.
Javascript
{
url: 'modules/cart_projects/saveData.php',
data: {
mydata: postData
}
}
PHP
$_POST['mydata'];
If you need to decode the JSON:
json_decode($_POST['mydata']);

Display object in javascript

I write a script to make an ajax call here is my code
function ajax_post(obj) {
obj = '#'+ obj;
var formData = $(obj).serializeArray();
$.ajax({
url: '__core/info.php',
type:'get',
dataType: 'json',
data: formData,
success: function(resp){
alert(resp);
}
})
}
and here is my info.php
$last_Res = theme::get_last_themes_desk(); //$last_Res is an array
echo(json_encode($last_Res));
but when alert it shows return object object ..... what should i do if datatype is json should i convert it to another format ? $last_Res is an array
In response to your comment (showing the response data, which is an array, containing a single object):
//resp = [{"id":"2","name":"babak_theme","sh_describ":"support css3 and ie 9 ","rate":"3","time":"2"}];
resp = resp[0];
alert('id => ' + resp.id + ', Name => ' + resp.name);//etc...
Will serve you just fine...
$last_Res is an associative array, most likely. JS doesn't have assoc arrays, but converts these to objects/ object literals:
//php:
$foo = array('foo' => 'bar');
//in JS:
var foo = {foo: 'bar'};
alert(foo);//alerts [object Object]
console.log(foo);//shows you what properties/prototypes/methods the object has
That's all there is too it. To access the data:
for (var prop in resp)
{//for "assoc arrays"
if (resp.hasOwnProperty(prop))
{
alert(prop + ' => '+resp[prop]);
}
}
for (var i=0;i<resp.length;i++)
{//for regular arrays
alert(i + ' => ' + resp[i])'
}
In your info.php, you should set the Content-Type header to application/json to indicate what you are returning:
header('Content-Type: application/json');
you haven't posted the json format. usually you can access resp. values like this:
if the json format is:
data['index']['subindex1'] = 'value1'
data['index']['subindex2'] = 'value2'
you can
alert(resp.index.subindex1);

Categories