returning multiple variables in JSON/PHP - php

Basically, i'm using an JSON response from a local PHP file to append data inside a div, currently it's only returning one variable, in which the code i'm using is shown here :
$.ajax({
url: "functions/ajax.php",
data: "func=auto",
type: "GET",
dataType: "json",
success: function(data){
$.each(data.search, function (i, v) {
$div = $('.bs-docs-example');
$div.append('+ v +');
});
},
error: function (jqXHR, textStatus, errorThrown){
console.log('Error ' + jqXHR);
}
});
The code which is returning the JSON is currently
while($row = mysql_fetch_assoc($res)) {
$search[] = $row['number'];
}
echo json_encode($search);
What i want to do is something like this
while($row = mysql_fetch_assoc($res)) {
$search[] = $row['number'];
$search[] = $row['name'];
}
echo json_encode($search);
But if i was to do the following, how would i access both number and name since in the success on the jQuery it's parsing using $.each(data.search, function (i, v) { which means the original $search[] = $row['number'] is now stored inside v
would i do something like v['name'] v['number'] or is that completely wrong ?

You'll want to pass an associative array to json_encode:
$search['number'] = $row['number'];
$search['name'] = $row['name'];
json_encode($search);
Or, if there will be multiple rows of results, as an array of associative arrays:
while($row = mysql_fetch_assoc($res)) {
$search[] = $row;
}
And then access the values in JavaScript by name:
var name = v['name'];
Or
var name = v[0]['name']
If you're using multiple rows of results.

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

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

how to fetch the array data from database query in a php file to ajax sucess data

i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;

How to get MySQL data into correct array structure

I just finished getting a script to work by using a hard coded array like so:
dataArray[0] =[50,10,0.3,0.25,50,"FFF",3];
dataArray[1] =[50,10,0.3,0.2,50,"FFF",3];
....
dataArray[5] =[50,20,0.5,0.7,120,"FF0",4];
I put the contents of dataArray into a db table so I could eliminate the hard coded array.
I'm returning the data in a string from MySql with PHP, and a data dump shows that the number of values and the values themselves are correct.
However, I'm apparently not coding the data capture correctly because I'm not ending up with an array like my hard coded array (I need to maintain the structure of my hard coded array).
Here's the code for the db read:
function getSomeData(){
$.ajax({
type: "GET",
url: "GetSomeData.php",
dataType: "text",
success:function(result){
setSomeData(result);
}
});
}
var someDataArray = new Array();
function setSomeData(resultData){
var resData = resultData.split('^');//record split
for(var i = 0; i < resData.length; i++){
someDataArray[i] = resData[i].split('#');//field split
someDataArray[i].pop();//removes array element occupied by '^'
if(i == resData.length - 1){
setDataArray();
}
}
}
This for loop in setDataArray() doesn't create the correct array structure because someDataArray[x] is just a string:
var dataArray = new Array();
function setDataArray(){
for(var i = 0; i < dataArray.length; i++){
dataArray[i] = someDataArray[i];
}
}
So I tried putting someDataArray[x] in an array like so:
dataArray[i] = [someDataArray[i]];
But that didn't work either.
I've spent the 2 days trying to puzzle this out, reading blogs, and experimenting with everything I could think of, but no luck. I think it's a simple solution but I just can't get it.
Help?
EDIT:
After learning a bit about JSON and json_encode I now have my script working. I wanted to post the way I did it to acknowledge that I received some valuable advice from Pat Burke. The code below may not be what he had in mind but I massaged it until it worked. But I don't really understand why it works, so I'll have to do some more reading on json_encode I think.
Note that using dataType:"json" in the ajax call threw an error.
//GetSomeData.php
$return_arr = array();
$query1 = "SELECT * FROM mytable ORDER BY idx ASC";
$result = mysql_query($query1) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result)){
$resultArray = array();
$resultArray[] = (int)$row['dc'];
$resultArray[] = (int)$row['smlspc'];
$resultArray[] = (float)$row['sclx'];
$resultArray[] = (float)$row['scly'];
$resultArray[] = (int)$row['lgspc'];
$resultArray[] = (int)$row['colr'];
$resultArray[] = (int)$row['diam'];
if(count($resultArray) == 7){
array_push($return_arr, $resultArray);
}
}
echo json_encode($return_arr);
mysql_free_result($result);
//new js
function getSomeData(){
resultData = new Array();
$.ajax({
type: "GET",
url: "GetSomeData.php",
dataType: "text",
//dataType: "json", //using this threw an error (see below)
success:function(result){
resultData = $.parseJSON(result);
$("#p1").append("resultData.length =" + resultData.length + "<br />");
//resultData.length =114 (it's a string not an array)
$("#p1").append("resultData =" + resultData + "<br />");
//resultData =
//[[50,10,0.375,0.25,50,0,0],
//[50,10,0.3,0.2,50,0,1],
//[50,10,0.6,0.4,0,0,2],
//[50,0,0.4,0.4,0,0,3],
//[50,0,0.4,0.4,0,0,3]]
for(var i = 0; i < resultData.length; i++){
$("#p1").append("resultData[" + i + "] =" + resultData[i] + "<br />");
//data displayed with dataType: "text"
//resultData[0] =50,10,0.375,0.25,50,0,0
//resultData[1] =50,10,0.3,0.2,50,0,1
//resultData[2] =50,10,0.6,0.4,0,0,2
//resultData[3] =50,0,0.4,0.4,0,0,3
//resultData[4] =50,0,0.4,0.4,0,0,3
//data displayed with dataType: "json"
//resultData is null
}
},
//this has no effect with either dataType: "text" or dataType: "json"
contentType: 'application/json'
});
}
if someDataArray[i] is a string of values separated by commas, you could do
dataArray[i] = someDataArray[i].split(',')

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