How to display data from a JSON array using jQuery - php

How can I get the array data from a JSON sent back by my php script?
PHP code:
<?php
//connects to database
include 'connect.php';
$callback = $_GET['callback'];
$query = mysql_query("SELECT * FROM users");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$out_string = json_encode($rows);
print $callback.'('.$out_string.');';
?>
The php code above puts all of user table's rows into an array and JSONencodes it. It is then sent back to this script:
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
});
How can I display each row from the JSON array sent back?
For example the data will be sent back is:
([{"name":"user1","link":"google.com","approve":"true"},{"name":"user2","link":"yahoo.com","approve":"true"},{"name":"user3","link":"wikipedia.com","approve":"true"}]);
How would I use javascript (jQuery) to display it out like this:
Name: User1 , Link: google.com , Approve:True
Name: User2 , Link: yahoo.com , Approve:True
Name: User3 , Link: wikipedia.com , Approve:True

When you done print $callback.'('.$out_string.');'; you've ruined JSON formatted string. Send back in array instead then loop on through your rows and display data.
$out_string = json_encode(array('callback' => $callback, 'rows' => $rows));

You should do
function(data) {
$.each(data, function(){
$('#result').append('<p>Name:'+this.name+' Link:'+this.link+' Approve'+this.approve+'</p>');
});
}
fiddle here http://jsfiddle.net/hUkWK/

$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
$.each(data, function(i, item) {
$("#mycontainer").append("<p>Name: " + item.name + "</p>");
$("#mycontainer").append("<p>Link: " + item.link + "</p>");
});
});

Related

json_encode for more than 2 arrays

I have 2 tables to be retrieved from database with 2 different queries and needs to be encoded in json and send to ajax.The issue is I am not able to pass 2 json's to ajax .
I have tried with echo json_encode(array($data1,$data2)); but it is not working.
//My php code
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1['value1'] = $row['value1'];
$data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2['value2'] = $row['value2'];
$data2['value3'] = $row['value3'];
}
echo json_encode(array($data1,$data2));
//My AJAX code
$(document).ready(function(){
$('#Form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"json",
success:function(data){
//main
alert(data.value1);
},
error:function(err){
alert(err);
}
});
});
});
Kindly help in solving this issue.Thanks in advance
In PHP:
echo json_encode(array($data1, $data2));
In AJAX:
var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
console.log(this.value2 + ',' + this.value3);
});
EDIT:
After a whole year, I just noticed that the initial PHP code was wrong, because the loop for the sql result would overwrite each time the values of the array. So, the correct one is this:
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}
echo json_encode(array($data1,$data2));
Your code is fine, you just have to handle the two arrays within your success function:
success: function(data){
var object1 = data[0];
var object2 = data[1];
// Do whatever you like to do with them
}

handling multiple db rows with ajax and json

I have a mysql database, I am using ajax to query it via php, it works fine when only a single row is returned it errors out with this when multiple rows are returned.
"xhr=[object Object]
textStatus=parsererror
errorThrown= SyntaxError: Unexpected token { in JSON at position 221"
Here is the code I am using, any help would be much appreciated.
$('button').click(function(){
event.preventDefault();
var box = document.getElementById('machine');
var rdata;
var id= box.options[box.selectedIndex].text;
$.ajax({
url: 'machine_report.php',
data: 'machine=' + id,
dataType: 'json',
success: function(rdata)
{
var uid = rdata[0];
var date = rdata[1];
var time = rdata[2];
var machine =rdata[3];
var reps = rdata[4];
var sets = rdata[5];
var weight = rdata[6];
var settings = rdata[7];
$('#status').html("<b>id: </b>"+uid+"<b> date: </b>"+date + "<b> Machine: </b>" + machine + "<b> reps: </b>" + reps + "<b> sets: </b>" +
sets + "<b> weight: </b>" + weight + "<b> settings: </b>" + settings);
},
error: function(xhr,textStatus, errorThrown) {
$("#status").html("xhr=" + xhr + "textStatus=" + textStatus + "errorThrown= " + errorThrown);
}
});
});
PHP Code
<?php
require_once("connect.php");
$machine = $_GET['machine'];
$mysql="SELECT * FROM workouts WHERE machine LIKE '$machine' ORDER BY uid DESC";
$result=mysqli_query($con,$mysql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$rowCount = mysqli_affected_rows($con);
while($row = mysqli_fetch_array($result)){
$date = $row['date'];
$time = $row['time'];
$machine = $row['machine'];
$reps = $row['reps'];
$sets = $row['sets'];
$weight = $row['weight'];
$settings = $row['settings'];
echo json_encode($row);
}
?>
Your PHP code is outputting one term at time so it will give response in following way.
{name:"abc",age:21}{name:"pqr",age:12}
which is not an valid json if you are passing multiple JSON Objects then you have to create collection of it.(which is simply a array of objects) The valid json for above json will be
[{name:"abc",age:21}{name:"pqr",age:12}]
You can produce this by first catching all the database rows into one array and then pass this array to json_encode
while($row=mysqli_fetch($result)
$rows[] = $row;
echo json_encode($rows);
All the above stuff is to do at the server side.
Now let's look at the client side.
Your Javascript code look fine except for success function because it is written for handling only one object.
Server response returns the data as array of json objects so first you have to iterate the array and then write a code for single object something like this
success:function(data) {
for(var i in data) {
var Row = data[i] // it will contain your single object
//console.log function is used for debugging purpose only you can find more about it by googling.
console.log(Row.name) // you can access it's member like this
// do other stuff such as dom manipulation.
}
}
NOTE: you can also use JQuery's $.each to traverse an array.

Can not retrieve data json from the server using ajax on cordova

I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);

Printing Specific JSON array elements in Javascript

A PHP script obtains data from a MySQL database and returns an array to javascript using JSON. I can get the results but I cannot get them to print them out individually.
The PHP code -
header('Content-type:application/json');
$link = #new mysqli(_HOST, _USER, _PASS, _DB); //constants
if(mysqli_connect_errno())
{
//failure
}
else
{
//success
$sqlQuery = "SELECT COL1, COL2 FROM TABLE"; //the query should return two
//columns from every selected row
$mix = array(); //array to return using JSON
$result = $link->query($sqlQuery);
if ($result->num_rows <= 0)
{
//no data
}
else
{
while ($row = $result->fetch_assoc()) //fetch loop
{
$mix["C1"][] = $row['COL1'];
$mix["C2"][] = $row['COL2'];
}
}
$result->free();
// Close connection
$link->close();
}
print json_encode($mix); //this line wont show up in previous code formatting block for some reason.
The Javascript / jQuery code -
$.ajax({ // ajax call
url: 'serv.php', // server page
data: 'fetch=1', //ignore any data
dataType: 'json', // server return type
success: function(data) // on success
{
for (var i in data) {
$('#someDiv').append( i + " = " + data[i] + '<br>');
}
}
});
The output, as expected is like this -
C1 = 1,2
C2 = A,B
What I want to accomplish is to put these data (1,2,A,B) inside a form table element. And to do that I need to pick the every element of C1 or C2 individually.
How can I accomplish this?
I've found the solution myself.
The following ajax call works-
$.ajax({ // ajax call
url: 'serv.php', // server page
data: 'fetch=1', //ignore any data
dataType: 'json', // server return type
success: function(data) // on success
{
for (var i in data["C1"]) {
$('#someDiv').append( i + " = " + data["C1"][i] + '<br>');
}
for (var i in data["C2"]) {
$('#someDiv').append( i + " = " + data["C2"][i] + '<br>');
}
}
});
Instead of accessing the data, I've tried to access the indices inside data. It was so simple.

is php json_encode & AJAX breaking my array?

I'm grabbing some database entries, creating a 2D array and then passing them to js with AJAX. But when I loop through the array in javascript, it's an "undefined" mess. The console log for dbArray works fine, so I know the PHP/AJAX is working. Not sure what I am doing wrong with the loop...
PHP ('load-words.php):
$query = mysql_query("
SELECT * FROM words
ORDER BY RAND()
LIMIT 50
") or die(mysql_error());
$dbArray = array();
while ($row = mysql_fetch_assoc($query)) {
$word_phrase = stripslashes($row['word_phrase']);
$description = stripslashes($row['description']);
// construct a 2D array containing each word and description
$dbArray[] = array($word_phrase,$description);
};
echo json_encode($dbArray);
Javascript:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) {
console.log(dbArray);
var items = "<ul>";
for (var i in dbArray) {
items += "<li><a href='#'><b>" + dbArray[i][0] + ' : ' + dbArray[i][1] + "</a></li>";
}
items += "</ul>";
div = $('#dbArray');
div.html(items);
}
});
I guess this is failing because jQuery is interpreting the AJAX response as a string, since your PHP is not outputting a JSON header and your AJAX is not stipulating JSON. This is easily tested:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) { alert(typeof dbArray); /* "string"? */ }
});
Try
$.ajax({
url: 'func/load-words.php',
dataType: 'json', //<-- now we explicitly expect JSON
success: function(dbArray) { alert(typeof dbArray); /* "object"? */ }
});

Categories