jquery ajax get database results using php json encode - php

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

Related

How to fetch data row by row from mysql table, queries coded in php, using jquery (AJAX)?

I am a beginner in Ajax. I want to fetch data row from Subject Table consist of only one column Subject as varchar(100), defined in MySQL DB. Following is my php code.
Data.php
<?php
$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " .mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo $row["SUBJECT"];
//I Want This Value to Be received in my Jquery Page
//So that i can take certain action based on each Subject.
//For example creating a select box child elements,options.
}
?>
Jquery.js
$(document).ready(function()
{
var response='';
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET'
success: function(text)
{
response=text;
}
});
});
$("body").append("<select> /*Get values here as options*/ </select>");
});
But The Desired action is getting values row by row like:-
1st row value comes-> take certain action in jquery;
2nd row value comes-> take sertain action..;
.
.
so on.
Data.php
<?php
$con=#mysqli_connect("","root","root","DBTemp");
# Instead of that use header 500 to let javascript side know there is a real error.
if (mysqli_connect_errno())
{
echo "Could not connect to database : ". mysqli_connect_error();
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit();
}
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
if (mysqli_error($con))
{
echo "Query failed : ".mysqli_error($con);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit();
}
$options = array();
# populate options arrey with using table's id field as key
# and subject field as value.
while($row = mysqli_fetch_assoc($result))
{
$options[$row['id']] = $row['subject'];
}
# return json encoded array to parse from javascript.
echo json_encode($options);
Data.php will output :
{"1":"Subject ID 1","2":"Subject ID 3"}
Jquery.js
$(document).ready(function()
{
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET',
dataType: 'json', // Let jQuery know returned data is json.
success: function(result)
{
$.each(result, function(id, subject) {
# Loop through results and add an option to select box.
$("#ajaxpopulate").append( new Option(subject,id) )
});
}
});
});
});
Page.html , inside the body. This select box will populated from ajax request.
<select id="ajaxpopulate"></select>
I would have the php function return a json response. You could do this in two ways either construct the JSON manually through your while statement server side or use the json_encode PHP function and echo that server side. That way when the data is returned client side in your ajax response you can parse the JSON data to a JSON object JSON.parse(json); and then control row by row the data in a structured way.
Hope this helps!
1) You need to use data structure like an array and pass it as a json response to your ajax call.
2) You need to iterate through your json array and that is where you can process each row separately and create nested select options.
UPDATE
$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: "
.mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
$jsonResult = [];
while($row = mysqli_fetch_assoc($result))
{
$jsonResult[] = $row["SUBJECT"];
}
echo json_encode($jsonResult);
An jquery should look like this
$(document).ready(function()
{
var response='';
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET'
dataType : 'JSON',
success: function(data)
{
//Alert should return an array of your subjects
//If it does then you need to iterate through this array and create options manually.
alert(data);
}
});
});
$("body").append("<select> /*Get values here as options*/ </select>");
});

JSON_ENCODE converts all array values to string in AJAX Request

I execute a simple AJAX Request, where i select some data from a mysql database. When i pass my Array back to Javascript, it always converts all Values in my Array into String, doesn't matter if its datatype was integer or boolean in my database.
EDIT:
I just found out, that MySQLi always converts datatypes to string, so I guess thats the problem. json_encode works fine.. https://stackoverflow.com/a/5323169/4720149
SQL Statement
function getAll()
{
// Get all buildings
$db = new db();
$sql = "SELECT * FROM building";
$result = $db->runQuery($sql);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
PHP Controller File
function getBuildings(){
$bu_db = new Building_Model();
$buildings = $bu_db->getAll();
echo json_encode($buildings);
}
Javascript file
var data = {
action: "getBuildings"
};
$.ajax({
type: "POST",
dataType: "json",
url: "controller/Building.php",
data: data,
success: function(data) {
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error in AJAX Request: " + textStatus + ", " + errorThrown);
}
});
Instead of keeping the original datatypes from the database, it turns all values into Strings:
Output
[Object, Object, Object, Object, Obje...]
>0: Object
>1: Object
>2: Object
>3: Object
ActiveCost: "20"
BuildEfc: "0"
BuildSfx: "0"
BuildingEfc: "0"
BuildingID: "1"
Name: "Vogtei I"
ResidentLvLNeeded: "0"
...
Does anybody know this problem?
Thanks in Advance.
What PHP version do you use?
Try:
echo json_encode($buildings, JSON_NUMERIC_CHECK );
Javascript has dynamic data types. So there is no specific data type for int string etc. same var object can hold all the data types. It will dynamically identify the type based on the operations you do on those variables.

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.

JSON.parse: unexpected character

I'm trying to pass a json from php jquery, after getting into an array of sql query and get the following javascript error.
JSON.parse: unexpected character
The function to return result of sql:
public function selectassocSql($sql){
$i = 0;
$resSelect = array();
mysql_query("SET NAMES 'utf8'");
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) )
{
$resSelect[$i] = $row;
$i++;
}
mysql_free_result($result);
return $resSelect;
}
After use this function in this way,
$sql = "SELECT id, code, name FROM table WHERE code LIKE '%$codcli%' ";
$v = $data->selectassocSql($sql);
echo json_encode($v, JSON_FORCE_OBJECT);
And the javascript code is this:
$('#formclientes').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = $.parseJSON(data);
}
})
})
How I can correct this error and how I can read a json from jquery?
You don't need the $.parseJSON call as jQuery automatically does it because if you don't specify a dataType property jQuery tries to guess it and calls the correct function to parse the response before the data is handled to the success function
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = data;
}
})
check out also this question Why is 'jQuery.parseJSON' not necessary?
I just ran into this in FF10.0.2 with data that looked like:
[ { "firstName": 'Joe', "lastName": 'Smith' } ]
(with multiple objects in the array - shortened for clarity)
It actually parsed OK using eval, though, instead of JSON.parse. (I'm not using jQuery here.)
The problem went away when I changed ' to " for the values:
[ { "firstName": "Joe", "lastName": "Smith" } ]
I thought the " requirement was only for property names, not data values.

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