Sending a multidimensional array with ajax - php

I have multidimensional array on client side, when I send that array to a PHP server, the array is received as string.
My code like this
let data_barang = [];
var nama_barang = $("#nama_barang_add").val();
var id_barang = $("#nama_barang_add").data("id_barang");
var perkiraan = $("#nama_barang_add").data("perkiraan");
var qty = $("#qty_add").val();
var satuan = $("#satuan_add").val();
data_barang.push([nama_barang, qty, satuan, id_barang, perkiraan]);
$.ajax({
url: '<?= base_url("Admin/Pengadaan/tambahSPB") ?>',
type: 'POST',
dataType: 'json',
data: {
id_rab: id_rab,
tgl_order: tgl_order,
id_supplier: id_supplier,
kode_supplier: kode_supplier,
alamat_supplier: alamat_supplier,
nama_supplier: nama_supplier,
provinsi_supplier: provinsi_supplier,
data_barang: data_barang // data barang is multidimensional array
},
success: function(data) {
alert(data.data_barang);
});
Server side code:
$data_barang[] = $this->request->getPost("data_barang");
$dataStatus = [
"message" => $message,
"detail" => $data_detail,
"data_barang" => $data_barang
];
echo json_encode($dataStatus);
I tried to use json.stringifiy on the client side and on server side I use json_decode, but it did not work

convert your array to string with JSON.stringify
data: {
id_rab: id_rab,
tgl_order: tgl_order,
id_supplier: id_supplier,
kode_supplier: kode_supplier,
alamat_supplier: alamat_supplier,
nama_supplier: nama_supplier,
provinsi_supplier: provinsi_supplier,
data_barang: JSON.stringify(data_barang) // data barang is multidimensional array
}
you can check array with
$data = json_decode($_POST['data_barang']);
print_r($data);

Related

Data sent from Ajax to codeigniter controller

I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);

PHP parse array posted from jQuery

I have this jQuery code that adds to an array inside an $each loop:
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
new_file_edits.push(JSON.stringify(new_edit));
jQuery new_file_edits array output
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
and im trying to post it to call.php like this:
$.ajax({
type: "POST",
url: "/call.php",
data: "edit_files="+ arrayVarHere,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
alert(+msg);
}
});
In the PHP file call.php i have this code:
if(isset($_POST['edit_files'])){
$edit_array = $_POST['edit_files'];
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
but i get this error and i cant figure out how to fix it, been googling it for a while now...
error:
Warning: Invalid argument supplied for foreach() in /home2/dddd/public_html/call.php on line 237
Line 237: foreach($edit_array as $key => $value){
Any help is much appreciated!
-Morten
EDIT 1:
I changed $edit_array = $_POST['edit_files']; to $edit_array = array($_POST['edit_files']);
And now it outputs:
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
How do i go from here with the foreach($edit_array as $key => $value){ part?
Edit 2:
i build my arrayVarHere like this:
$.each( $selected_files_array, function( index, value ){
//i get $file_id, $new_file_realname and $new_file_folder with some code here
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
arrayVarHere.push(JSON.stringify(new_edit));
});
change your code like this:
data: "edit_files="+ arrayVarHere,
call json data by json_decode in call.php
if(isset($_POST['edit_files'])){
$edit_array = json_decode($_POST['edit_files'],true); //return array
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
in your ajax alert should be
success: function(msg){
alert(msg); //remove plus sign ,this can output `NaN`
}
check edit_array is array print_r($edit_array);
check contentType is used form data then correct otherwise used json type
if form data then check data: edit_files[]: arrayVarHere,
It returns this array
Array ( [0] => [{"file_id":"1857","file_realname":"aq53pop_460sv[1].mp4","file_folder":"/"},{"file_id":"1859","file_realname":"aKqbD8Q_460sv[1].mp4","file_folder":"/"},{"file_id":"1856","file_realname":"aDopymK_700b[1].jpg","file_folder":"/"}] )
how can i loop the array and access file_id value etc?
The way you are passing Data to PHP may not be that ideal. Here is what might get you started:
PHP: call.php
<?php
$data0 = isset($_POST['data_0']) ? json_decode($_POST['data_0'], true) : null;
$data1 = isset($_POST['data_1']) ? json_decode($_POST['data_1'], true) : null;
$data2 = isset($_POST['data_2']) ? json_decode($_POST['data_2'], true) : null;
$arrData = array(
'data0' => $data0,
'data1' => $data1,
'data2' => $data2,
);
foreach($arrData as $dataKey=>$dataObject){
$tempFileID = $dataObject->file_id;
$tempFileName = $dataObject->file_realname;
$tempFileFolder = $dataObject->file_folder;
// DO SOMETHING WITH THESE DATA AND THEN BUILD UP A RESPONSE FOR AJAX + SEND IT...
// UNCOMMENT TO SEE THE DATA IN YOUR NETWORKS CONSOLE BUT
// IF YOU DO THIS (SINCE YOU EXPECT JSON RESPONSE) YOUR AJAX WILL RESPOND WITH AN ERROR...
// var_dump($dataObject);
}
// RESPOND WITH THE SAME DATA YOU RECEIVED FROM AJAX: JUST FOR TESTING PURPOSES...
die( json_encode($arrData));
?>
JAVASCRIPT: BUILDING THE DATA FOR PHP
<script type="text/javascript">
var dataForPHP = {};
var iCount = 0;
$.each( $selected_files_array, function( index, value ){
var keyName = "data_" + iCount;
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
dataForPHP[keyName] = new_edit;
iCount++;
});
</script>
JAVASCRIPT: AJAX REQUEST
<script type="text/javascript">
$.ajax({
type : "POST",
url : "/call.php",
datatype : "JSON",
data : dataForPHP,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
if(msg){
alert("Ajax Succeeded");
console.log(msg);
}
}
});
</script>

How to create a two-dimensional array in PHP and iterate through it with Javascript

Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});

Display object in javascript

I write a script to make an ajax call here is my code
function ajax_post(obj) {
obj = '#'+ obj;
var formData = $(obj).serializeArray();
$.ajax({
url: '__core/info.php',
type:'get',
dataType: 'json',
data: formData,
success: function(resp){
alert(resp);
}
})
}
and here is my info.php
$last_Res = theme::get_last_themes_desk(); //$last_Res is an array
echo(json_encode($last_Res));
but when alert it shows return object object ..... what should i do if datatype is json should i convert it to another format ? $last_Res is an array
In response to your comment (showing the response data, which is an array, containing a single object):
//resp = [{"id":"2","name":"babak_theme","sh_describ":"support css3 and ie 9 ","rate":"3","time":"2"}];
resp = resp[0];
alert('id => ' + resp.id + ', Name => ' + resp.name);//etc...
Will serve you just fine...
$last_Res is an associative array, most likely. JS doesn't have assoc arrays, but converts these to objects/ object literals:
//php:
$foo = array('foo' => 'bar');
//in JS:
var foo = {foo: 'bar'};
alert(foo);//alerts [object Object]
console.log(foo);//shows you what properties/prototypes/methods the object has
That's all there is too it. To access the data:
for (var prop in resp)
{//for "assoc arrays"
if (resp.hasOwnProperty(prop))
{
alert(prop + ' => '+resp[prop]);
}
}
for (var i=0;i<resp.length;i++)
{//for regular arrays
alert(i + ' => ' + resp[i])'
}
In your info.php, you should set the Content-Type header to application/json to indicate what you are returning:
header('Content-Type: application/json');
you haven't posted the json format. usually you can access resp. values like this:
if the json format is:
data['index']['subindex1'] = 'value1'
data['index']['subindex2'] = 'value2'
you can
alert(resp.index.subindex1);

How Print json Array in Javascript

PHP: Code:
$category_searchresult = $db->db_query("SELECT category_code, category_name, category_comment FROM qa_categories WHERE ".$search_by." LIKE '%".$search_string."%'");
$i=1;
$qa = array();
while($categories_query_result = mysql_fetch_array($category_searchresult))
{
$qa[$i][] = $categories_query_result['category_code'];
$qa[$i][] = $categories_query_result['category_name'];
$qa[$i][] = $categories_query_result['category_comment'];
$i++;
}
echo json_encode($qa);
JS Code:
$.ajax({
type: "POST",
url: "ajax_js.php",
data: search_data,
cache: false,
success: function(search_result) {
//Print Here
});
Current Output IS from PHP:
{"1":["4BA3CC","Fontaneria","Para la Casa"],"2":["CF0345","Herramientas","Herramients de Hogar"],"3":["1265CA","Luces","Luces de todo tipo"],"4":["4C4C9F","Vidrios","Reflectores de auto"]}
Many Thank's
Add a
dataType: 'json'
to your .ajax() call. That will tell jQuery to decode the JSON string from PHP back into a native Javascript data structure. Alternatively, you can take the data parameter in the success handler and explicitly do the decoding yourself:
success: function(data) {
var data = jquery.parseJSON(data);
}
Not quiet sure what the output should be but this is the code you can use to traverse a json object:
for(var key in search_result) {
var result = search_result[key];
//result is an array, so you can traverse or access each value by the key
// or you can join all the values together
var joinedValues = result.join(' | ');
//joinedValues will be something like '4BA3CC|Fontaneria|Para la Case'
}
You may want to set those values into a container object in the page to diplay them of course.
Hope this helps.

Categories