How to get values of encoded json using php in ajax response? - javascript

echo json_encode(array('out' => $out, 'total' => $total ));
Hi, I am getting a JSON data as below using the above PHP code.
var result = {"out":"[{\"tax\":\"SGST#9%\",\"percent\":7.75},{\"tax\":\"CGST#9%\",\"percent\":7.75},{\"tax\":\"SGST#2.5%\",\"percent\":3.11},{\"tax\":\"CGST#2.5%\",\"percent\":3.11}]","total":210}
I need to get the elements in a separate variable like below
var out = [{"tax":"SGST#9%","percent":7.75},{"tax":"CGST#9%","percent":7.75},{"tax":"SGST#2.5%","percent":3.11},{"tax":"CGST#2.5%","percent":3.11}];
var total = 210;
I tried so far with the below codes.
result = JSON.stringify(result);
result = result.replace(/\\/g, "");
var obj3 = JSON.parse(result);
alert(obj3[0]);
But i am not getting any output.

The basic problem is that $out is JSON to start with (so it ends up being double encoded), but it doesn't make sense for it to be JSON in the context.
You could just convert it to a PHP data structure before converting the wider array to JSON:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
If you don't want to touch the PHP, you can work around that in JavaScript:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
?>
var out_json = result.out;
var out = JSON.parse(out_json);

In your Ajax setup, add JSON
dataType: 'JSON',
Then in your success function,
success: function(result) {
console.log(result.tax);//gives you the value for the tax key provided it's defined in the php response array
},

Related

How can I access jquery Stringified array elements using PHP?

I use the following to post to a PHP page, showing the result in the message div:
let x = JSON.stringify($('#my-form').serializeArray());
$.post("processjs.php", {data:x})
.done(function(result, status, xhr) {
$("#message").html(result)
})
That results in the following array:
[{"name":"AccountName","value":"TestAcct"},{"name":"AccountID","value":"FR-62"},{"name":"Domain","value":"TestDomain"},{"name":"Status","value":"Enabled"},{"name":"ConfigurationSetName","value":"WLOD-1"},{"name":"SecConfVersion","value":"4"},{"name":"LastUpdated","value":"2022-12-1"},{"name":"MostCurrentVersion","value":"Yes"},{"name":"NotCurrentVersionReason","value":"None"},{"name":"RouterCount","value":"3"},{"name":"CustomerASN","value":"999999"},{"name":"ConfiguredP","value":"127"},{"name":"IPInstalled","value":"No"},{"name":"SharedGroup","value":"True"},{"name":"overlap","value":"False"},{"name":"POverlap","value":"False"},{"name":"ACLSDConfigured","value":"No"},{"name":"ACESDCount","value":"432"}]
How can I use PHP to access the array elements? Why are all of the keys and values prefaced with "name:" or "value:"?
I have tried using the following to access a key:
$json = json_decode(stripslashes($_POST['data']),true);
$AccountName = $json['AccountName'];
echo $AccountName;
But I always get the same message:
Undefined array key "AccountName"
I have tried using the following to access a key:
$json = json_decode(stripslashes($_POST['data']),true);
$AccountName = $json['AccountName'];
echo $AccountName;
I have also tried things like
$AccountName = $json[0]['AccountName'];
or
$AccountName = $json[0];
and also
$AccountName = $json[1];
In your sample request, AccountName is not a index, it is value of name index in a object inside a array.
Please try like this.
$json = json_decode(stripslashes($_POST['data']),true);
foreach($json as $inner){
$name = $inner['name']; //"AccountName" .... Here you will get value in $name a name .
$accountId = $inner['value']; //"TestAcct" ... Here you will get value in $accountId as "TestAcct" name .
}
Outputs are stated only for first iteration of foreach .

shorter way to collect and send data without a form

I have some (15) input, select, and textarea tags on page - without a form
need to collect their values and insert them into a database
this code works fine, but I hope there is a way to short it
on client side - maybe some kind of serialize
on server side - especially on execute statement - maybe some kind of loop
$('#btn_send').on('click', function(){
let obj = {};
$('input, select, textarea').each(function(){
let a = $(this).attr('name');
obj[a] = $(this).val();
});
let str = JSON.stringify(obj);
$.post('reg.php', {fn: 'btn_send', args: [str]}, function(data){
console.log(data);
});
});
reg.php
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute([
":aname" => $obj->name,
":agender" => $obj->gender,
//... and so on - 15 items
]);
echo 'success';
}
Based on your code sample, it looks like the elements of your object have the same names as the columns in your table. In that case, you can simplify your code by converting the incoming JSON to an array rather than an object and utilising the fact that PDOStatement::execute allows the array keys to not include the : in the names:
$obj = json_decode($str, true);
// here are table columns
$cols = array_keys($obj);
$a = implode(',', $cols);
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute($obj);
Should the behaviour of execute change in the future, you can make an array with the keys preceded with : using array_combine and array_map:
array_combine(array_map(function ($k) { return ":$k"; }, $cols), $obj)
You would then pass this array to execute in place of $obj.
Something I made not sure if it even compiles, just was bored this is how I would do the 15 items or so part.
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$sqlArray = array();
foreach($obj as $key => $value) {
$sqlArray[]= array(":a".$key => $value);
}
$st->execute($sqlArray);
echo 'success';
}
Edit: I looked at Nick's answer it seems you don't even need to do all the hard stuff I did, you can just pass $obj wow they made it so easy now

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

Call array from php

If i want to call an array from php into typescript also in an array form how i can do it
this is my php code :
$AccessQuery = "SELECT name,lastname,phone,email
FROM user
INNER JOIN access ON id
WHERE id
$userQuery = mysqli_query($localhost, $AccessQuery) or trigger_error(mysql_error(), E_USER_ERROR);
while ($AccessQueryRow = mysqli_fetch_assoc($userQuery)) {
$AccessData[] = array(
'id' => $AccessQueryRow['id'],
'code' => $AccessQueryRow['code'],
);
};
$arr = array(
"user_access_details" => $AccessData,
);
echo json_encode($arr);
I try this in order to encoded and use each one as a variable in an array
var jsonData = JSON.parse(data);
what i really want is how i can put each menu_id in an array field :
arr= {id1,id2}
the same for the code
how i can put each menu_id in an array field : arr= {id1,id2}
If you only care about the ids, ignore the code values. Get the array of the shape you want in PHP.
while ($AccessQueryRow = mysqli_fetch_assoc($userQuery)) {
$AccessData[] = $AccessQueryRow['id'];
};
echo json_encode($AccessData);
On the client side:
var jsonData = JSON.parse(data);
The result will be the array of just ids.

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

Categories

Resources