Call array from php - javascript

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.

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 .

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'id_paket' at row 1

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'id_paket' at
row 1 (SQL: insert into tbl_pesanan (id_paket, kode_bmn,
kode_unit, jenis_barang, kuantitas, satuan_ukuran,
status_pesanan) values (18,18, 1010101002,1010101002, 1001,1001,
ASus,ASus, 6,6, UNit,UNit, 1))
what happened, can you help me?
public function store_pesanan(request $request,$id){
if(!Session::get('login')){
return redirect('/login')->with('alert','Kamu harus login dulu');
}
else{
DB::table('tbl_paket')
->where('id_paket',$id)
->update(['status_paket' => $request->status_paket]);
$data = new ModelPesanan();
$data->id_paket = implode(',', $request->input('id_paket'));
$data->kode_bmn = implode(',', $request->input('kode_bmn'));
$data->kode_unit = implode(',', $request->input('kode_unit'));
$data->jenis_barang = implode(',', $request->input('jenis_barang'));
$data->kuantitas = implode(',', $request->input('kuantitas'));
$data->satuan_ukuran = implode(',', $request->input('satuan_ukuran'));
$data->status_pesanan = $request->get('status_pesanan');
$data->save();
Alert::success('Sukses!', 'Berhasil Menambahkan Pesanan!');
return redirect ('/daftar_paket');
}
}
The issue seems to be that you are trying to insert a value in the field id_paket that is too long. Check the type and size of id_paket and compare to what your query is sending: 18,18
You should not try to save arrays into a single field unless they are intended to be kept as a json.
I think you are trying to create two ModelPesanan? if so, assuming id_paket is a foreign key and the key of the id_paket array is the same for all the other arrays in the request then you can try:
DB::table('tbl_paket')
->where('id_paket',$id)
->update(['status_paket' => $request->status_paket]);
foreach($request->input('id_paket') as $index => $idPaket){
$data = new ModelPesanan();
$data->id_paket = $request->input('id_paket')[$index];
$data->kode_bmn = $request->input('kode_bmn')[$index];
$data->kode_unit = $request->input('kode_unit')[$index];
$data->jenis_barang = $request->input('jenis_barang')[$index];
$data->kuantitas = $request->input('kuantitas')[$index];
$data->satuan_ukuran = $request->input('satuan_ukuran')[$index];
$data->status_pesanan = $request->get('status_pesanan');
$data->save();
}
Alert::success('Sukses!', 'Berhasil Menambahkan Pesanan!');
return redirect ('/daftar_paket');

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. ;)

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

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
},

How to split array and store each value in localstorage

I have array like below,
Array
(
[0] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
[1] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
[2] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png
)
I want to split above array and each key value has to stored in localStorage like 'front'=> array[0],'back'=>array[1],'side'=>array[0].
How to achieve this. ?
If your array is in JAVASCRIPT, you can access to the array elements directly, so you can call the localStorage function directly...
var yourArray = [
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
];
localStorage.setItem('front',yourArray[0]);
localStorage.setItem('back',yourArray[1]);
localStorage.setItem('side',yourArray[2]);
If your array is in PHP, you'll have to add a <script> element...
<?php
$yourarray = array(
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png"
);
?>
<script>
localStorage.setItem('front','<?=$yourarray[0]?>');
localStorage.setItem('back','<?=$yourarray[1]?>');
localStorage.setItem('side','<?=$yourarray[2]?>');
</script>
you can have separate script (test.php) and have a json out as below
<?php
$arr1 = array(
0 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
1 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
2 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
);
$arr2 = array('front'=>'', 'back'=>'', 'side'=>'');
// assign values from array 1 to array 2
$arr2['front'] = $arr1[0];
$arr2['back'] = $arr1[1];
$arr2['side'] = $arr1[2];
echo json_encode($arr2);
then from javascript you can access this object as follows and store it in local storage
<script>
$(document).ready(function () {
$.get("test.php", function (data, status) {
var out = JSON.parse(data);
// Store in local storage
localStorage.setItem("frontElem", out.front);
localStorage.setItem("backElem", out.back);
localStorage.setItem("sideElem", out.side);
var side = localStorage.getItem("sideElem", out.side);
console.log(side)
});
});
</script>

Categories

Resources