php json_decode and Jquery Nestable - php

I'm using jquery Nestable (http://dbushell.github.io/Nestable/).
I'm trying to intercept data from it when I change order on mine nestable elements..
$('.dd').nestable().on('change', function() {
var json_text = $('.dd').nestable('serialize');
$.post("/includes/processes/core.php", {
cmd: 'nestable',
table: table,
data: json_text
}, function(response){
alert(response);
});
});
In core.php I've done:
$data = $_POST['data'];
$data = json_decode($data, true);
function parseJsonArray($jsonArray, $parentID = 0) {
$return = array();
foreach ($jsonArray as $subArray) {
$returnSubSubArray = array();
if (isset($subArray['children'])) {
$returnSubSubArray = parseJsonArray($subArray['children'], $subArray['id']);
}
$return[] = array('id' => $subArray['id'], 'parentID' => $parentID);
$return = array_merge($return, $returnSubSubArray);
}
return $return;
}
$readbleArray = parseJsonArray($data);
Than I've to manipulate this array but I can't go on because response is:
"json_decode() expects parameter 1 to be string, array given in core.php on line (where is "$data = json_decode($data, true;")"
If I change json_decode($data, true) with json_encode($data) this is the response:
"Invalid argument supplied for foreach() in core.php on line (where is "foreach ($jsonArray as $subArray);")"
Please Help me..

Try removing this line because $.post doesn't do json encoding.
$data = json_decode($data, true);

Use JSON.stringify. It will turn your javascript object into a JSON string, which will allow you to post it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You can than decode it in PHP. To do this, in your jQuery code replace this:
data: json_text
With:
data: {json_text: JSON.stringify(json_text)}

Related

update json replacing variable input from form in php

Greeting, I'm new to PHP, and currently looking for a way to edit json.
I have a form to input the key that wants to edit. I echo the input from form and successfully got the output showing but it didn't pass to json file to update. The code is as below.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = json_decode($data, true);
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
//you this post contain test?
//test is the the button when i submit the form
if (array_key_exists('test',$_POST))
{
testfun();
}
Am I missing something?
Try my code.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = array(json_decode($data, true));
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
if (array_key_exists('test',$_POST))
{
testfun();
}
As you mention in the comments, the content of the $json_arr is:
{"CELL_NAME":"1234A","#25":"remark value"}
So when you trying to access in:
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
it has no key for $value at CELL_NAME key.
I guess your $data from the file should be like that (an array of JSONs):
$data = '[{"CELL_NAME":"1234A","#25":"remark value"}, {"CELL_NAME":"1234B","#25":"remark value"}]';
Now you can do this and it will work:
$arr = json_decode($data, true);
foreach ($arr as $key => $value) {
if ($value['CELL_NAME'] == "1234A") // you can change with $_POST['in_cell']
$arr[$key]['#25'] = "test"; // you can change with $_POST['in_remark']
}

JSON parse URL with PHP JSON decode

I have JSON data:
{"took":3,
"timed_out":false,
"_shards":{ "total":5,
"successful":5,
"failed":0
},
"hits":{"total":105,
"max_score":1.0,
"hits":[
{"_index":"csv",
"_type":"logs",
"_id":"AVeyr-BQodQ9UhW1sdW0",
"_score":1.0,
"_source":{"message":"james,wonder\r",
"#version":"1",
"#timestamp":"2016-10-11T07:40:52.332Z",
"path":"D:\\logstash-2.4.0\\bin\\Book1.csv",
"host":"CHNL-LT-544",
"fname":"fa1368a93aa39b2346329c1734be1f4b",
"lname":"wonder"
}
},
{"_index":"csv",
"_type":"logs",
"_id":"AVeyr-BQodQ9UhW1sdW1",
"_score":1.0,
"_source":{"message":"muskaan, wonder\r",
"#version":"1",
"#timestamp":"2016-10-11T07:40:52.332Z",
"path":"D:\\logstash-2.4.0\\bin\\Book1.csv",
"host":"CHNL-LT-544",
"fname":"479085e94d305129527fa80978613e95",
"lname":"wonder"}
},
{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdW3","_score":1.0,"_source":{"message":"altimetrik,india\r","#version":"1","#timestamp":"2016-10-11T07:40:52.333Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"8b3ecf275832c79b36d62d74f47257c9","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdW8","_score":1.0,"_source":{"message":"kool,indiae\r","#version":"1","#timestamp":"2016-10-11T07:40:52.335Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"d2edbdce885720c70f38f36748c37600","lname":"indiae"}},{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdXA","_score":1.0,"_source":{"message":"ds,dssd\r","#version":"1","#timestamp":"2016-10-11T07:40:52.336Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"91594a75bc6bfb0ec800d4f454e1fe87","lname":"dssd"}},{"_index":"csv","_type":"logs","_id":"AVeytJ0iodQ9UhW1sdXf","_score":1.0,"_source":{"message":"kool,india\r","#version":"1","#timestamp":"2016-10-11T07:46:02.839Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"d2edbdce885720c70f38f36748c37600","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytJ0iodQ9UhW1sdXi","_score":1.0,"_source":{"message":"karnataka,india\r","#version":"1","#timestamp":"2016-10-11T07:46:02.840Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"2a0785caed6bfd2ffb6ad5a449f2bd0e","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdXq","_score":1.0,"_source":{"message":"james,wonder\r","#version":"1","#timestamp":"2016-10-11T07:48:39.550Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"fa1368a93aa39b2346329c1734be1f4b","lname":"wonder"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdX0","_score":1.0,"_source":{"message":"rajasthan,india\r","#version":"1","#timestamp":"2016-10-11T07:48:39.558Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"449b07d9038569b2d69243dadfae0371","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdX5","_score":1.0,"_source":{"message":"najeeb,shariff\r","#version":"1","#timestamp":"2016-10-11T07:48:39.573Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"be7a5e98258338fa63086f44e8bd1850","lname":"shariff"}}]}}
I want to print only 2 fields from this JSON; fname and lname. Please tell me how I can achieve this using PHP.
$url = 'localhost:9200/csv/_search';;
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['hits'] as $item) {
print $item['fname'];
}
But getting error Undefined index
$url = 'localhost:9200/csv/_search';;
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['hits']['hits'] as $item) {
echo "<p>{$item['_source']['fname']}</p>";
echo "<p>{$item['_source']['lname']}</p>";
}
Array path of fname and lname goes like [hits][hits][0][_source][fname] and [hits][hits][0][_source][lname]. [hits][hits] should be iterated in the loop to access each _source element.
As RiggsFolly said, you need to do print_r($json) to see how the array is structured especially when you encounter nested arrays.
Hope it helps!

Can't change value in json

I have a .json file with player name, mail address, field name and score on that field. Like this:
{"0":{"name":"test","password":"test","mail":"test#test.test","test3":0,"test2":0},"1":{"...
I want to change the score at one field, but I can't. I tried this way:
$jsonn = file_get_contents('data/userdata.json');
$arrayy = json_decode($jsonn, true);
$field = $_SESSION['fieldname'];
$arrayy[$felhasznev][$palya] = $pontszam;
And I also tried this but not helped:
$jsonn = file_get_contents('data/userdata.json');
$arrayy = json_decode($jsonn, true);
$field = $_SESSION['fieldname'];
foreach ($arrayy as $key => $valuee){
if($valuee['name'] == $username){
$valuee[$field] = $score;
}
}
I'm beginner in JSON so maybe something trivial...
Function json_decode parse json file to objects, you're using associative array, to have an associative array you have to pass a second argument as true, like:
<?php
$file = file_get_contents("file.json");
$players = json_decode($file, true);
$err = json_last_error();
if ($err != JSON_ERROR_NONE) {
print_r($err);
die("Error in json file :/");
}
var_dump($players);
foreach ($players as $key => $val) {
if ($players[$key]["name"] == "test") {
$players[$key]["test3"] = $players[$key]["test3"] + 1;
$players[$key]["test2"] = $players[$key]["test2"] + 1;
}
}
var_dump($players);
file_put_contents("new_file.json", json_encode($players));
(1) In your sample json, there is value (0) not enclosed in double quote (parsing error!).
(2) the first code should work if json is ok.
(3) in the second code, you skipped the "id" identifier (if json is ok).

Error while trying to read posted json data in php

I have the following problem. When i am trying to read some json data that are posted from an html page, i'm facing with the following error "Trying to get property of non-object on line".
Jquery script to create the json
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
Jquery for posting to php
$.post("page.php",{jsonData: JSON.stringify(json),
customer: $("#cusID").val()},function(data){});
PHP file
$json = json_decode($_POST['jsonData']);
foreach($json as $value){
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
Thanks in advance.
Thereafter:
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
You have:
Object[data][0] = array('serialNumber' => ...);
Need:
$json = json_decode($_POST['jsonData'][0]);
or
$json = json_decode($_POST['jsonData']);
foreach($json as $row){
foreach($row as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
}
json_decode without second parameter returns result as php object. You have to pass true as second parameter. Also your data are in $json['data'], not $json:
$json = json_decode($_POST['jsonData'], true);
foreach($json['data'] as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}

How can I display JSON data using PHP

I have already created a dynamic JSON file.
My code is:
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro)) {
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
How can I get data from the JSON file? Using a while loop or anything similar?
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($res))
{
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
First, you have mistake on line 2
mysql_fetch_array($res)
AND NOT
mysql_fetch_array($respro)
Second, Use file_get_contents and json_decode functions
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
Thanks
This is how you see the posted json data in your php file.
I would prefer that:
$json_string=json_encode($records);
you must put the header
header('Content-Type: application/json;charset=utf-8');
and other side
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
First of all the way you are writing to the file inside the while loop is wrong.. Because you are unneccesarily calling the file_put_contents() again and again which is simply degrading your code performance..
So rewrite your code to this..
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro))
{
$records[]= $rowpro;
}
file_put_contents("product_file.json",json_encode($records));
To read the JSON data , make use of file_get_contents()
Like this..
$jsonData = file_get_contents("product_file.json");
echo $jsonData; //<--- Prints your JSON
In PHP ,
header('Content-Type: application/json;charset=utf-8');
$str = file_get_contents('product_file.json');
$jsonData = json_decode($str, true); //json decode
And in jquery you can use jQuery.getJSON example ,
$.getJSON( "product_file.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

Categories