$.each() loop through json not looping - php

i have an ajax call that gets back json i am trying to send the items returned to specific input text id's.
This is the ajax:
$.ajax({
url: "php/myfirstfile.php",
type: "POST",
data: $("#frameroof").serialize(),
cache: false,
dataType: "json",
success: function (json) {
$.each(json, function () {
$.each(json, function (key, value) {
/// do stuff
$('#' + key ).val(value);
});
});
}
});
This is what is returned: [{"a-frame":"100"}][{"vertical":"350"}]
it looks im getting 2 arrays when i need one to loop over. Im not sure.
Here is the php
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
$results = array();
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
//dump all data from associative array converted from query result
echo (json_encode($results,true));
$result->free();
}
}
}
}
$short_connect->close();

I believe your problem is pretty simple. Inside of your loop you're initializing the results array and you're outputting it. This causes a new results array to be created, serialized to JSON, and outputted for every iteration of the loop. Thus what you're sending the browser is not JSON, but several chunks of JSON all run together.
This is the basic idea of what you need to be doing:
<?php
// Initialize the output data
$results = array();
foreach($something as $a_something) {
$results[] = do_something_to($a_something);
}
//Serialize and send the output data
echo (json_encode($results,true));
Rearranging your code with that pattern in mind produces this (which ought to work for you, and will return an empty array to the browser if your if conditions aren't met or the query doesn't return anything):
<?php
// Initialize the output data
$results = array();
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
//Add to the output data
$results[] = $row;
}
$result->free();
}
}
}
}
$short_connect->close();
//Serialize and send the output data
//dump all data from associative array converted from query result
echo (json_encode($results,true));

Related

AngularJS ng-repeat not showing data in table

I have a problem with output from MySQL
getCustomers.php is
$query="select distinct c.ancestry, c.trusted from members c order by c.id";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = json_encode($row);
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
and controler code:
app.controller('customersCrtl', function ($scope, $http, $timeout) {
$http.get('ajax/getCustomers.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 100; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
Problem is that i get from MySQL this format (e.g.):
["{\"ancestry\":\"12865794218\",\"trusted\":\"128\"}"]
but expectable is:
[{"ancestry":"1286794218","trusted":"126"}]
so, if I write constants in data it works perfectly fine
$scope.list = [{"ancestry":"1286794218","trusted":"126"}];
Thanks for any help.
You're double-encoding your response. The backslashes are there because the second application of json_encode escapes the double quotes in the output of the first one. Remove the json_encode from inside your while loop.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row; // don't encode here
}
}
Then just encode it once afterward (as you already are.)
$json_response = json_encode($arr);
I think you need to use header('Content-Type: application/json'); in your php code, so that the server responds with a JSON content type.
There is also a duplicate json_encode in your code, inside your while loop so you're doing duplicate json encoding, hence the unexpected output
use JSON.parse() on your response. JSON.parse docs

Recover php mysql query with ajax/json?

How to recover data from research by json? I would like to recover the separate items as the result show in php page to create new elements, for example recover item.f, item.m to create new elements like item.f < / div> < span > item.m. .. thank you
(error presented at)
Error Can not read property of items " of null
Php page ( does the query )
if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
function chatHeartbeat() {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$items = '';
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$items. = << < EOD
{
"s": "0",
"f": "{$chat['de']}",
"m": "{$chat['mensagem']}",
"i": "{$chat['img']}"
},
EOD;
}
}
Index ( calls the pair query present the results - error here - need help here)
$.ajax({
url: "asd.php?action=chatheartbeat",
cache: false,
dataType: "json",
success: function(data) {
$.each(data.items, function(i, item) {
alert(item.f)
});
}
});
As #jeroen says dont manually generate JSON Strings use json_encode() to create a JSONString from a PHP array or an object.
if ($_GET['action'] == "chatheartbeat") {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$t - new stdClass();
$t->s = "0";
$t->f = $chat['de'];
$t->m = $chat['mensagem'];
$t->i = $chat['img'];
$chatBoxes[] = $t;
}
$items = json_encode($chatBoxes);
// now just echo $items to return it to the javascript in the browser
// here or later in the code if there is more to your code than you showed us
echo $items;
}
References:
json_encode()
json_decode()
Thank you all for the help, I managed to solve the problem as follows
Php page ( does the query )
$result = mysql_query("SELECT * FROM mensagens");
while( $array = mysql_fetch_assoc($result)){
$table[]= array("de"=>$array['de'],"mensagem"=>$array['mensagem']); }
echo json_encode($table);
Index
$.ajax({
url: 'asd.php',
dataType: 'json',
success: function(data)
{
for($i=0; $i < data.length; $i++){
$("#chatbox_"+chatboxtitle+" .chatboxcontent").append(
'<div class="message"><span class="from">'+data[$i].de+':
</span><span class=content">'+data[$i].mensagem+'</span></div>');
}}
});

No Ajax response post value [duplicate]

I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.

Echo all json_encoded rows

I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.

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;

Categories