Printing Specific JSON array elements in Javascript - php

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.

Related

AJAX Response and PHP Loop

I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.
However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?
AJAX:
$.ajax({
type: "POST",
url: 'feed.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
$.each(data, function(key, value) {
// here I want to loop through the returned results - for example
$("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
});
}
});
feed.php
if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
$query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
// this query returns approx. 20 results
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data["Direction"] = $row['Direction'];
$data["CardNo"] = $row['CardNo'];
$data["SerialNo"] = $row['SerialNo'];
}
echo json_encode($data);
}
Also in my PHP, should I be using a while or if statement?
You're using a single $data object and resetting its contents each time. You want to build an array of objects:
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = array(
"Direction" => $row['Direction'],
"CardNo" => $row['CardNo'],
"SerialNo" => $row['SerialNo']
);
}
echo json_encode($data);
Followed by:
success: function(data) {
$.each(data, function(key, value) {
$("#transactionTable").prepend(
'<tr><td>' + value.SerialNo + '</td>' +
'<td>' + value.CardNo + '</td>' +
'<td>'+ value.Direction +'</td></tr>');
});
}
In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.
Many solutions exist, but you have to do something like
$data["Direction"][] = $row['Direction'];
$data["CardNo"][] = $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];
or better:
$data[] = $row;
Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo
note: not tested

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.

Select multiple rows into array and send them via AJAX

I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

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