How to pass multidimensional array via ajax and display it? - php

I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});

You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))

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

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();

looping through multiple arrays in JQuery from a multi array JSON response

Am I on the wrong path here?
I have a ajax call to upload some files.
I then create a array on the PHP side and send it back as JSON. But im not sure if the JSON format is correct.
Problem is I want to populate a dataTable with the returned JSON data, but I having difficulty reading the data. If its a single file then its fine and it works, but as soon as its more than one file
PHP CODE
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
$json = array();
$json[] = $row;
echo json_encode($json);
on the JQuery/AJAX call side
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: './inc/MediaScripts.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(html) {
var t = $('#vidlib_dtable').DataTable();
var obj = eval(html);
$.each(obj, function(key,value) {
t.row.add( [
value.name,
value.title,
value.path,
value.duration,
value.uploaded_date,
value.uploaded_by,
value.keyword,
value.comment,
] ).draw();
});
});
});
});
The original return has more columns, hence the above columns in the dataTable add.
The return looks like multiple (singular) JSON arrays.
[{"uuid":"236","name":"Koala.jpg"}]
[{"uuid":"237","name":"Lighthouse.jpg"}]
I was wondering if it should not take the shape of something like this
[{"uuid":"236","name":"Koala.jpg"}, {"uuid":"237","name":"Lighthouse.jpg"}]
If the format that I receive the data in is fine, how do I go about looping trhough the multiple arrays on the JQuery side?
That's because you are echo'ing 3 different JSON object arrays.
Each time your loop iterates you echo, the loop then re-creates the array and echo's the new JSON array.
$json = array();
//forloop{ START
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
array_push($json, $row);
//} END
echo json_encode($json);
Initialize your array before the loop, and echo it after it's been fully created.

jQuery AJAX Update a dropdown select onChange return an empty string

Can someone tell me what I'am doing wrong here, console.log() returns me an empty string instead of an array ?
I want to update the second selectbox once onChange is triggered on first selectbox but I can't retrieve the data. When I'am doing a var_dump($results) it successfully shows an array of items, but return $results returns me an empty string.
Here how it looks like:
a javascript:
function _getNestedSelectOptions(activeComponent){
$.ajax({
type: "POST",
url: "/backend/categories/get_nested_options/" + activeComponent
}).done(function(html){
console.log(html);
});
}
And this is a php code controllers/backend/categories.php:
public function get_nested_options($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
$categoriesDropdownOptions = array();
$this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);
var_dump($categoriesDropdownOptions); // <-- THIS WORKS AND SHOWS AN ARRAY OF ITEMS
//return $categoriesDropdownOptions; // <-- THIS DOES NOT WORKING
}
here is an output on console.log():
array (size=3)
7 => string 'Administrators' ->(length=14)
8 => string 'Managers' ->(length=8)
9 => string 'Users' ->(length=5)
You can try to get json in js, use
In controller:
public function getNestedOptions($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
$categoriesDropdownOptions = array();
$this->categories_model->getNestedOptions($categoriesDropdownOptions, categoriesResult);
echo json_encode($categoriesDropdownOptions); exit;
}
$.ajax({
dataType: "json",
type: "POST",
url: "/backend/categories/get_nested_options/" + activeComponent
data: data
}).done(function(data){
response = jQuery.parseJSON(data);
console.log(response);
});
you will get data in json format.
I managed to work it out by helps of #KA_lin (jQuery.parseJSON() didn't work, idk why) and #RameshMhetre, so thank you guys for your helps.
This is an AJAX in categories.js:
function _getNestedSelectOptions(activeComponent, targetName){
// Url in proper JSON format with datas
var url = "/backend/categories/get_nested_options/";
// Target selectbox to apply modifications on it
var ddb = $(targetName);
// Save first dummy/null option
var top = ddb.find('option:first');
$.ajax({
type: 'POST',
url: url + activeComponent,
dataType: 'json',
beforeSend: function(){
// Disable selectbox
ddb.prop('disabled', true);
},
success: function(data){
// Insert saved first dummy/null option
ddb.empty().append(top);
$.each(data, function (index, value) {
// Append html data to target dropdown element
ddb.append('<option val="'+ value.id +'">'+ value.title +'</option>');
});
// Re-enable selectbox
ddb.prop('disabled', false);
}
});
}
controllers/backend/categories.php:
public function get_nested_options($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
// Get an array of properly constructed parents and childs
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
// Prepare an array of dropdown option values (without keys)
$categoriesDropdownOptions = array();
// Fill in an array with appropriate values for use with form_dropdown($array)
$this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);
// Prepare an array for JSON output (with keys)
$results = array();
// Modify a raw array with specific keys for use in JSON
foreach($categoriesDropdownOptions as $id => $title){
$results[] = array(
'id' => $id,
'title' => $title
);
}
// Set a proper page content and output JSON results
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($results));
}
And the views/backend/categories/form.php:
<fieldset>
<legend>Attributes</legend>
<label class="control-label" for="formCatCid">
Component name:
<div class="controls">
<?php
$componentDropdownExtra = 'class="span12" onChange="categories.getNestedSelectOptions(this.value, formCatPid);"';
echo form_dropdown('formCatCid', $componentDropdownOptions, set_value('formCatCid', $formCatCid), $componentDropdownExtra);
?>
</div>
</label>
<label class="control-label" for="formCatPid">
Category parent:
<div class="controls">
<?php
$categoriesDropdownExtra = 'class="span12"';
echo form_dropdown('formCatPid', $categoriesDropdownOptions, set_value('formCatPid', $formCatPid), $categoriesDropdownExtra);
?>
</div>
</label>
</fieldset>

How to end an array of json data, and echo another value?

I'm using php to return an array of data, with the command json_encode(). I want to also send some other data after I send this array. I'm using the jquery library. My php code is as follows:
<?php
//// Query
$sql = "SELECT gtn FROM $table WHERE gid < 10";
//// Open connection
$con = pg_connect("host=12.12.2.2 port=5434 dbname=spatial_data user=postgres password=****");
if (!$con){echo 'error connecting'; die; }
//// Run query
$query = pg_query($con, $sql);
$arrayData = array(); // Store results from query in arrays
//// Parse results
while($r = pg_fetch_row($query)) {
$arrayData[] = $r[0];
}
echo json_encode($arrayData);
//// Return metadata about calculation
//echo "$('#messages').html('Result returned for New York')";
//// close connection
pg_close($con);
?>
This php is responding to a jquery post command:
$.ajax({
type: "POST",
url: "/php/array_test_v3.php",
data:{vertices: pointlist},
success: function(arrayData){
//console.log(arrayData[0])
for(i=0;i<arrayData.length; i++){
setGeoJson(arrayData[i]);
}
},
dataType:'json'
});
This is a spatial database, and when I query the information, I also want to return some other values. For example, if the area is New York, I want to return an array of data and also the string New York. At the moment the line echo "$('#messages').html('Result returned for New York')"; just appends to the array of information. Is there a way that I can escape from the array, or do I need to have a separate post function to get this information.
Instead of echo json_encode($arrayData);, just fetch the meta data and then do:
echo json_encode(array(
'data' => $arrayData,
'meta' => $metaData
));
And then in JQuery:
success: function(result){
for(i=0;i<result.data.length; i++){
setGeoJson(result.data[i]);
}
// do something with result.meta
},
assuming you are using php.
make the array like this below
while($r = pg_fetch_row($query)) {
$arrayData[] = array('gtn'=>$r[0],'someotherkey'=>'someothervalue','anotherkey'=>'anothevalue');
}
echo json_encode($arrayData);
now in jquery you can do this
$.ajax({
type: "POST",
url: "/php/array_test_v3.php",
data:{vertices: pointlist},
success: function(arrayData){
$.each(arrayData,function(index,value){
setGeoJson(value.gtn);
$('#messages').html(value.someotherkey);
})
},
dataType:'json'
});
like this you can append or do any thing you like..

Categories