If I have, in javascript, something like:
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
What is the best method to pass it to php through an HTTP POST?
I've tried a jQuery plugin to convert the array to JSON. I've tried to create multiple hidden fields named "entries[]", each one with the JSON string. Somehow, I can't seem to decode my data with PHP's json_decode.
EDIT:
I tried changing the JSON plugin used to the one #Michal indicated and the results I get are the same:
Javascript
[
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"},
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"}
]
PHP Vardump:
string(756) "
[
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"},
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"}
]
"
When I use PHP's json_decode, I get NULL.
var_dump(json_decode($_REQUEST['entries']));
Output:
NULL
You need to convert JSON to a string (use JSON stringifier (https://github.com/douglascrockford/JSON-js) and POST the string (as a field value) to the PHP script which does json_decode()
Concat it using some characters like _ or %% then pass it to PHP.
In PHP file:
$ar = array();
$ar = explode('special_char',string pass from js);
echo "pre";print_r($ar);
echo "/pre";
well, the trouble seemed to be with the quotes that were being passed in the post, so i just replaced the quotes with open strings to my $_REQUEST.
Related
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.
I am trying to make a php page tp print json data for this i m using one paraeter for which i needed to fetch json from another url.I used the code given in other stackoverflow ans but it always giving 0.I tried everything but it always giving 0.My php code is:
<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');
$bookname=$_POST['bookname'];
$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);
echo 'data' + $json_data->results[0]->{'num'};
?>
My json data from other url is:
{"result":[{"avg":"3.9","num":"3"}]}
You see 0 printed because you're performing an addition + between the string data and a non-existent property. In PHP, to concatenate strings, do not use +; instead, use the dot . operator
In addition, because you're using true as the 2nd parameter to json_decode, what you get back is an array of arrays. Use the array notation [] rather than the object notation -> to access members.
$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3
Live demo
Hi I'm trying to insert the json array into my MySQL database.With array json data from android client.
[{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}]
If you want to store the array as a string, you can use JSON.stringify():
$string = [{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}];
$json = JSON.stringify($string);
The variable $json is then a simple string which can be inserted into MySQL easily.
You can then use:
var obj = JSON.parse($json);
To convert the string back to an array.
This method usually isn't recommended for performance reasons though, so you might alternatively want to break up the array and store each field individually.
Try this:
$json = serialize(json_array);
Use $jsonArray = json_decode($jsonStr);.
Then iterate the array as you want to save data in your mysql database.
you can use - serialize()
$json = '[{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}]';
$newJson = serialize(json_decode($json));
$newJson is ready to be inserted. and after fetching -
$data = unserialize($fetchedData); and then json_encode($data);
Im trying to pass a mulitidimensional Javascript array to another page on my site by:
using JSON.stringify on the array
assigning the resultant value to an input field
posting that field to the second page
using json_decode on the posted value
then var_dump to test
(echo'ing the posted variable directly just to see if it came through
at all)
Javascript on page one:
var JSONstr = JSON.stringify(fullInfoArray);
document.getElementById('JSONfullInfoArray').value= JSONstr;
php on page two:
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
The echo works fine but the var_dump returns NULL
What have I done wrong?
This got me fixed up:
$postedData = $_POST["JSONfullInfoArray"];
$tempData = str_replace("\\", "",$postedData);
$cleanData = json_decode($tempData);
var_dump($cleanData);
Im not sure why but the post was coming through with a bunch of "\" characters separating each variable in the string
Figured it out using json_last_error() as sugested by Bart which returned JSON_ERROR_SYNTAX
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to #Thisguyhastwothumbs
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
You'll need to check the contents of $_POST["JSONfullInfoArray"]. If something doesn't parse json_decode will just return null. This isn't very helpful so when null is returned you should check json_last_error() to get more info on what went wrong.
None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:
Javascript (added encodeURIComponent)
var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;
PHP (unchanged from the question)
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.
stripslashes(htmlspecialchars(JSON_DATA))
jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);`
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));
I just want to get my PHP array to a JS array, what am I doing wrong here?
PHP:
// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"]
JS:
var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);
Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).
An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.
If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.