Regarding Data table source data access - javascript

I have used the datatable ajax call for listing I received the below json data in ajax call:
{
"sEcho":1,
"iTotalRecords":"1",
"iTotalDisplayRecords":"1",
"aaData":[
["Demo to Mam","2"]
],
"countOfTotalRecords":2
}
How I can use the countOfTotalRecords var value on view page?

You've to decode your JSON data using json_decode, then you have an object. Looks something like this:
$json = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords"
:2}';
$decode = json_decode($json);
echo $decode->countOfTotalRecords; // this will display 2, regarding your data

use the below code
$str = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords":2}';
$arr = json_decode($str);
$tcount = $arr->countOfTotalRecords;
echo $tcount;

Related

Save data to JSON File in correct format - PHP

I am currently saving click co-ordinates to a JSON file through the use of the following code:
onmouseup = function(e){
var Clicks = {};
Clicks.state = {
cX: e.clientX,
cY: e.clientY,
}
$.ajax({
type : "GET",
url : "PHP/save_json.php",
data : {
state : JSON.stringify(Clicks.state)
}
});
}
<?php
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
fwrite($fh, $stringData);
fclose($fh)
?>
However with the above code I am saving the coordinates in the following incorrect format:
{"cX":467,"cY":374}{"cX":56,"cY":474}
Can anyone please help me to save the coordinates in a JSON array rather than in seperate JSON entries?
I would like the file to be as follows, were the coordinates are added onto the already existing JSON array within the file:
{
"ID":["1","2"],
"cX":["467","56"],
"cY":["374","474"]
}
What you need to do is:
Open the clicks.json file and read the entire contents.
Turn this into an instance of stdClass by using json_decode. This will give you a PHP object that you can modify using normal PHP functions and syntax.
Use json_decode on the JSON that you receive from your client.
Use array_push to push the new values from the client into the arrays stored in the file (something like array_push($fileJson->cX, $clientJson->cX);)
Use json_encode to encode $fileJson again.
Write it back to the file.
This assumes that the clicks.json file is already correctly formatted JSON with the arrays already created etc.
Given the current arrangement of the key and value bits, it's apparent that some sort of transformation is needed in the JSON data before it is written to the file. Where this transformation is done is definitely a matter of an opinion. However, assuming that you receive following JSON data in PHP:
[{"cX":467,"cY":374},{"cX":56,"cY":474}]
The PHP code can be written as (illustrated with static input):
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source = json_decode($string, true);
$json_array_target = array();
foreach($json_array_source as $key=>$value){
$json_array_target["ID"][] = $key + 1;
foreach($value as $sub_key => $sub_value){
$json_array_target[$sub_key][] = $sub_value;
}
}
$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);
If you were to echo $transformed_string;, you'd see:
{"ID":[1,2],"cX":[467,56],"cY":[374,474]}
Which is what will be written to the file.
You need load data to array, add new data and save back to file.
I think you don't need save numbers in strings.
These code create new file if not exists.
<?php
// test input data
if(isset($_GET['state']['cX']) &&
isset($_GET['state']['cY']) &&
is_numeric($_GET['state']['cX']) &&
is_numeric($_GET['state']['cY']) )
{
// ok
} else {
exit('Bad data format');
}
$myFile = __DIR__ . "/JSON/clicks.json";
// step 1, load data from file to array
$array = file_exists($myFile) ?
json_decode(file_get_contents($myFile), true) :
[];
// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];
// step 3, save array back to file
file_put_contents($myFile, json_encode($array));
Or you can use other file format where will be possible to append file. The easiest format for static structured data could be CSV
Use json_encode to convert your string to an object, then convert it back to a string using json_decode and the JSON_PRETTY_PRINT option.
$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);
http://php.net/manual/en/function.json-encode.php

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

JSON format issue in JavaScript

Following is my JavaScript code to get JSON data:
$(document).ready(function()
{
$.support.cors = true;
$.getJSON('http://example.com/root_dir/test_json.php', function(data1)
{
alert("data1= "+data1);
});
});
but the above alert shows me JSON in following format-
If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-
[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]
Following is my test_json.php code-
<?php
//Create an array
$json_response = array();
$row_array['name'] = 'AB';
$row_array['std'] = '7';
$row_array['number'] = '82';
array_push($json_response,$row_array);
$row_array['name'] = 'CD';
$row_array['std'] ='9';
$row_array['number'] = '90';
array_push($json_response,$row_array);
$row_array['name'] = 'PQ';
$row_array['std'] = '12';
$row_array['number'] = '79';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
getJSON decodes the JSON into a JavaScript data structure.
Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".
Nothing is going wrong. That is the expected behaviour.
If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.

Storing data from MySQL to PHP Array to return with JSON

I have a MySQL table with cols | btn_id | btn_title | btn_bg | btn_text |.
I am trying to get the data in the table to a php array and then return via JSON so the array can be used in the JS document requesting the PHP/MySQL Data. Respective of row and columns/index.
So far i have:
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
Q. Now i wish to return a JSON Array made from the array of data. How do i proceed here?
Note: I am horrible with arrays and not entirely sure i have the correct method above for my requirements, but i think it is correct.
Call json_encode after the loop:
header("Content-type: application/json");
echo json_encode($array);

How to create javascript array from database by php

I want to create a javascript array from databse like this:
var m = [
[one]
[two]
[three]
]
it is important that typeof m be object.
Use Json_encode
$phparray; // This is your php array
$jsArray = <?php echo json_encode($phparray); ?>;
//do stuff with $jsArray now

Categories

Resources