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

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.

Related

How to pass multidimensional array via ajax and display it?

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

jquery ajax get database results using php json encode

I have this php code that is call using jQuery ajax that queries a database and gets results and then json encode the results
//$rows is another query
foreach($rows as $row) {
$sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
$stmt = $db->prepare($sql);
$stmt->bindValue(':field', trim($row['field_1']));
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
}
The outputting json looks like this
[{"field1":"J1","field2":"0088","field3":"2928868"}][{"field1":"J2","field2":"0171","field3":"2928868"}][{"field1":"J2","field2":"0249","field3":"2928868"}]
The problem I'm getting is processing it in the Ajax response. What I would like to do i s loop through each of the array/rows and display the data but the responseText shows an error.
I thought it should look this but i don't know for definite.
[{"field1":"J1","field2":"0088","field3":"2928868"},{"field1":"J2","field2":"0171","field3":"2928868"},{"field1":"J2","field2":"0249","field3":"2928868"}]
My question is, am i doing the json_encode correctly and how do i output each of the rows?
$.ajax({
type: "POST",
url: "check.php",
data: { order: order },
dataType: "json",
cache: false,
success: function(response) {
if(response.length != 0) {
//output results here
}
else {
$('#foo').text('Order number not found!!');
}
// set the focus to the order input
$('#order').focus().val('');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
You should JSON encode the entire output, instead of outputting the json encoded version of each row:
$output = array();
//$rows is another query
foreach($rows as $row) {
$sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
$stmt = $db->prepare($sql);
$stmt->bindValue(':field', trim($row['field_1']));
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$output[] = $array;
}
echo json_encode($output);
Answering your question, to work with your JSON in JavaScript, you treat it as if it were an array of objects. You can even use jQuery to help loop through the results for you with $.each:
if(response.length != 0) {
$.each(response, function(index, row) {
console.log(row);
// Access your row variables like so:
// row.field1, row.field2, row.field3, etc.
}
}
If you prefer natively looping through, you can do the following:
// Let i start at zero. If the response array length is less than i, execute the block, then increment i by 1.
for(var i = 0; response.length < i; i += 1) {
}
Related Question / Further Reading: How to parse JSON in JavaScript

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

jQuery Post, PHP and MySQL Returning Data

I want to use jQuery to pull information from my database when I click a button.
i've managed to get console.log to display the following
[Object { id="16", user_to="Obadiah Stane", user_delivery_add1="The Lanesborough"}]
But I cant figure out how to pull each value for use in a Form.
Could someone help?
jQuery
$.post('/assets/inc/get-delivery-details.php', qString, function (data) {
console.log(data);
var json = $.parseJSON(data);
$('.addAddressDialog').html(json);
}, "json");
PHP
$q = "SELECT * FROM tbl_user_delivery WHERE id = '$selectedID'";
$sql = mysql_query($q);
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'id' => $row['id'],
'user_to' => $row['user_to'],
'user_delivery_add1' => $row['user_delivery_add1']
);
}
echo json_encode($results);
$.post('/assets/inc/get-delivery-details.php', qString, function (data) {
//var json = $.parseJSON(data); // don't need this line, because you've
// already set dataType json as fourth
// arguments of $.post()
// To get values
alert(data[0].id);
alert(data[0].user_to); // so on
// To set above values to a form fields
// just an example, don't know your form markup
$('input[name=id]').val(data[0].id); // so on
}, "json");
$('.addAddressDialog').html(json.id); will output 16 in your example.
After parsing the variable json, it becomes an object.

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