Sending an array to server side using $.getJSON - php

I am using $.getJSON() to pass some data to the server side (PHP, Codeigniter) and using the return data to do some work. The data that I am sending over to the server is in the form of an array.
Problem: When an associative array is sent to the server, no result is received on server side. However, if a normal array with numerical indexes is sent, the data is received on server side. How can I send an array of data over to the server?
JS Code (Not Working)
boundary_encoded[0]['testA'] = 'test';
boundary_encoded[0]['testB'] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
JS Code (Works)
boundary_encoded[0][0] = 'test0';
boundary_encoded[0][1] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
PHP Code
$boundary_encoded = $_GET['boundary_encoded'];
print_r($_GET);
Error Msg
<b>Notice</b>: Undefined index: boundary_encoded in <b>C:\xampp\htdocs\test\boundary\boundary_encoded_insert_into_db_ajax.php</b> on line <b>11</b><br />
Array
(
)
Working Result
Array
(
[boundary_encoded] => Array
(
[0] => Array
(
[0] => test
[1] => test1
)
)
)

The reason this isn't working is because JavaScript does not support associative arrays. This assignment:
boundary_encoded[0]['testA'] = 'test';
appears to work in JS because you can assign a new property to any object, arrays included. However they won't be enumerated in a for loop.
Instead, you must use an object literal:
boundary_encoded[0] = {'testA':'test'};
You can then use JSON.stringify to convert boundary_encoded to a JSON string, send that to the server, and use PHP's json_decode() function to convert the string back into an array of objects.

I would suggest using converting the arrays to JSON. If you can't do so in PHP (using the json_encode function), here are a couple of JS equivalents:
http://phpjs.org/functions/json_encode:457
http://www.openjs.com/scripts/data/json_encode.php

In your getJSON call, use
{boundary_encoded: JSON.stringify(boundary_encoded)},
instead of
{boundary_encoded: boundary_encoded},

Related

An empty JSON object produced by jquery code is wrongly parsed to an empty string in PHP code

I am passing a JSON object via ajax to my php file. Then I use the function json_encode, and save it to the database.
The problem is, when the JSON object is empty {}, then in PHP it is not an empty object/array, but it is an empty string "".
I need to deserialize it as encoded (empty JSON object), not as an empty string.
What am I doing wrong?
JQUERY:
_key = $(this).data('column-name');
_temp = {};
$(this).find('> .rc-picker-content > .rc-picker-item').each(function (__index, $__element) {
_temp[__index] = {};
_temp[__index] = $(this).attr('data-value');
});
_attr[_key] = _temp; //the variable which is sent via ajax to php
PHP
if (isset($_POST['value']) && is_array($_POST['value'])){
$_POST['value'] = json_encode($_POST['value']); //this hould be enmpty array not empty string
}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
It may help.
I found a solution.
I convert the object to string before sending it via ajax to my php file.
_temp = JSON.stringify(_temp);
This solution has already been proposed. I just had to restructure my code.

save value taken en $_POST in an array

I'am passing values from java (android) to a web service (php) : the structure should be an array because the webservice take an array and make a serach in that array so how could I passing an array in $_POST :
$interet= $_POST['interet'];
// must be an array like this : $interet =array('piano','flute','chien');
NB/: the contain of the array is dynamic , it may have One or even ten value
You can create in Java json:
String mStringArray[] = { "piano", "flute", "chien" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
after send it to php server, and in php do this:
$array = json_decode($_POST, true);

Send an associative array from Laravel function to CasperJS

I am new to CasperJS and laravel. I need a help, I want to send an associative array(all the contents in that array at once) to CasperJS from a function, currently i am encoding it using the JSON_encode as the CasperJS script doesn't take array. The following piece of code encodes the array and sends as one string. On the other side i am fetching the string in casperJS script and unable to decode the JSON. The format of json changes on reaching the casperJS script.
$array = array
(
[1] => http://www.xxxx.com,
[2] => http://www.yyyy.com,
[3] => http://www.zzzz.com
);
$data_fetch=json_encode($array);
$casperjs = new CasperJS;
$result = $casperjs->execute($this->script2,$data_fetch);
print_r($data_fetch);
which outputs after encoding the array
{"1":"http://www.xxxx.com","2":"http://www.yyyy.com","3":"http://www.zzzz.com"}
The CasperJS script
var system = require('system');
var casper = require('casper').create({
verbose: true,
logLevel: 'error',
pageSettings: {
loadImages: false,
loadPlugins: false
}
});
var data = system.args[4];
casper.start(function() {
var decode=json.stringify(data);
});
casper.run();
when you check the input in 'data' variable using console.log it is
{1:http://www.xxxx.com,2:http://www.yyyy.com,3:http://www.zzzz.com}
which is different from the json.encode it is omitting double quotes, because of different formats i am unable to decode the content.
Can anyone help why is it doing that way?? Any solution for this?? OR is there any other better way to pass an array to casper and return back the result as an array.

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

Parsing - JSON - Array of Arrays

A JSON array has the form:
[[a,b,c],[a,b,c],[a,b,c]]
Is there a better way than split?
No, this is most certainly not the best way to parse JSON. JSON parsers exist for a reason. Use them.
In JavaScript, use JSON.parse:
var input = '[[1,2,3],[1,2,3],[1,2,3]]';
var arrayOfArrays = JSON.parse(input);
In PHP, use json_decode:
$input = '[[1,2,3],[1,2,3],[1,2,3]]';
$arrayOfArrays = json_decode($input);
You do not need to use regular expressions. As has been mentioned, you must first have valid JSON to parse. Then it is a matter of using the tools already available to you.
So, given the valid JSON string [[1,2],[3,4]], we can write the following PHP:
$json = "[[1,2],[3,4]]";
$ar = json_decode($json);
print_r($ar);
Which results in:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
)
If you want to decode it in JavaScript, you have a couple options. First, if your environment is new enough (e.g. this list), then you can use the native JSON.parse function. If not, then you should use a library like json2.js to parse the JSON.
Assuming JSON.parse is available to you:
var inputJSON = "[[1,2],[3,4]]",
parsedJSON = JSON.parse(inputJSON);
alert(parsedJSON[0][0]); // 1
In JavaScript , I think you can use Eval() → eval() method...

Categories