looping through mySQL json_encode with jQuery - php

I'm struggling to retrieve and display results from PHP json_encode via JQuery. Any help appreciated. Here's my code php side:
$return_it = array();
$query= mysql_query("SELECT * FROM $tableName");
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$row_array[] = $row;
array_push($return_it,$row_array);
}
echo json_encode($return_it);
and on success I have this.
dataType: 'json',
success: function(data)
{
$.each(data, function() {
var name = data.name;
var values = data.values;
$('#output').append("<tr style=\"background-color:#ccc\"><td>id: </td><td> name: </td></tr><tr><td>"+name+"</td><td>"+values+"</td></tr>");
});
}
this is looping but returning undefined, I know I'm probably missing something obvious :-/

Your array nesting in php is unnecessary and doesn't match the way you are trying to parse the results. Just use the return_it array for each row
$return_it = array();
$query= mysql_query("SELECT * FROM $tableName");
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$return_it[] = $row;
//array_push($return_it,$row_array); /* remove */
}
echo json_encode($return_it);
The result in javascript currently would look like
[
[ {name:'foo',values:'123'} ],
[ {name:'foo2',values:'345'} ]
]
Without the extra nesting:
[
{name:'foo',values:'123'},
{name:'foo2',values:'345'}
]
This will not change the $.each parsing, rather you would need to look inside each sub array if maintain current structure.
You are however misisng critical arguments for $.each callback
$.each(data, function() {index, row){
var name = row.name;
});

I think it should be:
dataType: 'json',
success: function(data)
{
$.each(data, function(d) {
var name = d[0].name;
var values = d[0].values;
$('#output').append("<tr style=\"background-color:#ccc\"><td>id: </td><td> name: </td></tr><tr><td>"+name+"</td><td>"+values+"</td></tr>");
});
}
The each method applies a method to each element that is passed to the method. As it happens, you are not passing anything to function(), so you should add the parameter (in my example it is d) and manipulate d, rather than data.
As apparently you are nesting the json array (returing an array of single arrays) the d[0] part would return the attributes of the first element of your nested array, which, in your case would be your {name:"...",values:"..."}.
However, if you remove your nested JSON array as mentioned in another answer, then you don't need to add the d[0].name, and use only d.name as now each line of your JSON array is the collection of attributes, rather than an array of size 1, which would have the attributes.
Essentially you are encapsoulating your results. You should either remove the encapsoulation, or adjust the data parsing from JSON.
Hope this helps.

Related

Return to ajax with while loop through PHP

I have got this ajax
$.ajax({
type: "GET",
url: '../connect.php',
data: "OrB=" + ajaxsend+"&&IOr="+i,
success: function(data)
{
var x = $.parseJSON(data);
var el='<div class="CommentsAw Comment_Hs">\
<img src="../users/'+x[0]+'">\
<span>'+x[1]+'</span>\
<span class="s2">'+x[2]+'</span>\
</div>'
$(".F_W_comments").html().remove();
$(".F_W_comments").html(el);
}
});
and php
if (isset($_GET['OrB'])) {
$OB=$_GET['OrB'];
$I=$_GET['IOr'];
if ($OB=='OO') {
$OB='`Date` ASC';
}else if ($OB=='No') {
$OB='`Date` DESC';
}
$query=$con->query("SELECT id,comment FROM uploads WHERE Rand='$I'");
$row=$query->fetch_row();
$Commentsq=$con->query("SELECT * FROM (SELECT * FROM comments WHERE Post_id='$row[0]' ORDER BY $OB LIMIT 4) AS sub ORDER BY `DATE` ASC") or die($con->error);
while ($CommentRow=$Commentsq->fetch_row()) {
$CommenterPp=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$CommentRow[3]'");
$CommenterPicture=$CommenterPp->fetch_row();
$CommenterPp=$con->query("SELECT Username FROM users WHERE Id='$CommentRow[3]'");
$CommenterName=$CommenterPp->fetch_row();
echo json_encode(array($CommenterPicture,$CommenterName,$CommentRow));
}
}
But it gives me error in console like this one
VM654:2 Uncaught SyntaxError: Unexpected token [ in JSON at position 107
[["5734919677561.jpg"],["Murad"],["1842","3","21","1","2016-05-08 21:56:52"]]
[["5734919677561.jpg"],["Murad"],["1843","GOodm","21","1","2016-05-08 21:56:54"]]
[["5734919677561.jpg"],["Murad"],["1845","re","21","1","2016-05-08 21:56:54"]]
[["5734919677561.jpg"],["Murad"],["1844","re","21","1","2016-05-08 21:56:54"]]
What i want is connect.php to get data from database and then pass it to ajax.
But the result was nothing probably bcause there is some error in my code
Echoing several json-encoded strings does not mean a valid json.
What you need to do is json_encode your data and echo it once.
$commenters = array(); // result array
while ($CommentRow=$Commentsq->fetch_row()) {
$CommenterPp=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$CommentRow[3]'");
$CommenterPicture=$CommenterPp->fetch_row();
$CommenterPp=$con->query("SELECT Username FROM users WHERE Id='$CommentRow[3]'");
$CommenterName=$CommenterPp->fetch_row();
$commenters[] = array($CommenterPicture,$CommenterName,$CommentRow);
}
// while loop over
echo json_encode($commenters);
And in your js you should iterate over an array of objects, not a simple object, for example:
success: function(data) {
var x = $.parseJSON(data);
for (var k in x) {
console.log(x[k]);
}
}
Removing the data in the arrays for a moment, the resulting JSON was structured like this:
[][][][]
That's not valid JSON. The parser expects a single object or array, not several arrays concatenated together like that.
Instead of outputting the response in the loop, build the total response and output it once after the loop. Basically create an empty array before the while loop in PHP, then push elements onto the array within the loop, then echo the JSON-encoded array after the loop.
My PHP is very rusty, but in PHP-ish pseudo-code it would be structured like this:
$result = array();
while ($CommentRow=$Commentsq->fetch_row()) {
// other code...
$result[] = array($CommenterPicture,$CommenterName,$CommentRow);
}
echo json_encode($result);

Accessing JSON Object returned from PHP using Jquery Ajax

I am having trouble accessing the JSON data returned from my AJAX JQUERY call.
The AJAX executes correctly as does the query. I get the correct data returned; this consists of two arrays that I JSON_ENCODE. I need to be able to access both data sets independently.
It may make sense when you guys see the code:
**PHP**
$sql501 = "SELECT member,COUNT(member) as cont from loggederrors WHERE err = '".$hello."' GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
$count = array();
while($row56 = mysqli_fetch_assoc($result50)) {
array_push($member, $row56['member']);
array_push($count, $row56['cont']);
}
echo JSON_encode($member);
echo JSON_encode($count);
?>
$member and $count are arrays and when they are returned and logged in my AJAX success function they look like this :
["Missed Entry"]["1"]["Missed Entry","Overwrite"]["1","1"]
The data is in the right order but seems to repeat which I understand is because I am pushing in each iteration to the arrays. Its the closest I got because the order is correct. I have tried building an associative array and using various different mysqli outputs i.e num_rows, fetch_assoc
Previously when I have used JSON I have never had an issue and have key to access the data:
Here is the AJAX:
$.ajax({url: 'getstaffresults.php',
data: {stafftosend:stafftosend },
type: 'post',
async: 'true',
success: function(data){
console.log(data);
}
});
I have previously been able to access individual keys with data.keyIwantbut this is not coming out as expected. Any help is much appreciated.
The goal is to get access to the two arrays. I do not need access to values in the arrays if that makes sense.
I have tried building a 2d array and encoding that but again I had not way of accessing it.
I have tried JSON.stringyfy , JSON.parse
Try packing the two responses into an array and only echo'ing one response.
$sql501 = "SELECT member,COUNT(member) as cont from loggederrors WHERE err = '".$hello."' GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
$count = array();
while($row56 = mysqli_fetch_assoc($result50)) {
array_push($member, $row56['member']);
array_push($count, $row56['cont']);
}
$arrayResponse = array(
'member' => $member,
'count' => $count
);
echo JSON_encode($arrayResponse);
?>
I only suggest this because I am unsure if the javascript would parse to json strings side by side?
The nack it to create a single sensible PHP data structure and then convert it to json
You dont need 2 arrays for you information. Also if you echo 2 responces the likelyhood is the second will be lost in the ether.
So try this instead, create an array of arrays to return to the javascript code, which makes them easy to process here and in javascript.
$sql501 = "SELECT member,COUNT(member) as cont
from loggederrors
WHERE err = '".$hello."'
GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
while($row56 = mysqli_fetch_assoc($result50)) {
$member[] = array('member' => $row56['member'],
'cont' => $row56['cont']);
}
echo JSON_encode($member);
?>
In fact you can simplfy this even further to
$sql501 = "SELECT member,COUNT(member) as cont
from loggederrors
WHERE err = '".$hello."'
GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
while($row56 = mysqli_fetch_assoc($result50)) {
$member[] = $row56;
}
echo JSON_encode($member);
?>
Now change the javascript to add the dataType: 'json', property
$.ajax({url: 'getstaffresults.php',
data: {stafftosend:stafftosend },
type: 'post',
async: 'true',
dataType: 'json',
success: function(data){
console.log(data);
}
});
and the data should be converted to javascipt array automatically
In your php:
echo json_encode(['member' => $member, 'count' => $count]);
In javascript:
$.ajax({url: 'getstaffresults.php',
data: {stafftosend:stafftosend },
type: 'post',
async: 'true',
success: function(data){
var parsedData = JSON.parse(data);
console.log(parsedData);
}
});

Populate JS array from returned PHP/JSON

I have a JSON encoded array, to which i am returning to an AJAX request.
I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON array contents into a JS array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
You can use JSON.parse function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Adding to Safraz answer:
If you're using jQuery, there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json.
Below example shows you simple way to achieve this. There's simple json property accessing (result.message), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)

json dataType is not working in jquery ajax method

i'm just trying to query the database and display the result the jquery's ajax method but if i put the dataType property as json it is only logging the result which has only one object the following is my code:
//this is a method is an object which will be triggered after a selection was made
lister: function () {
//this is to target the object as it is inside an event
var self = users;
//the ajax call
$.ajax({
url: 'index.php',
type: 'POST',
data: self.config.form.serialize(),
//this is the dataType
dataType: 'json',
success: function (results) {
//this for logging the result
console.log(results);
}
});
}
the php code
if(isset($_POST['q']) && !empty($_POST['q'])){
$na = $_POST['q'];
$query = mysql_query("SELECT id,first_name, last_name
FROM users WHERE users.first_name LIKE '$na%'");
$num=mysql_num_rows($query);
if($num >= 1){
while($row = mysql_fetch_array($query)){
//encoding the result as json
echo json_encode($row);
}
} else{
echo "no results found ";
}
//here we return so it won't display all of the pages
return;
}
You are generating invalid JSON. You are encoding every row of your table independently, which generates something like this:
{"foo": "bar"}{"foo": "bar"}{"foo": "bar"}
This is isn't valid. It's just a concatenation of objects. What you need is an array of objects:
[{"foo": "bar"}, {"foo": "bar"}, {"foo": "bar"}]
You can achieve that by creating an array first, add each row to it and encode the array:
$data = array();
while(...) {
$data[] = $row;
}
echo json_encode($data);
Another problem is that in case no results are found, you are simple returning plain text, not JSON. This will probably result in an error on the client side. If you tell jQuery to expect JSON, then every possible response must be JSON. So you might want something like:
echo json_encode(array('error' => 'no results found'));
or even better, return an empty array:
echo json_encode(array());
It should be fairly obvious to the client that no results have been found if an empty array is returned.

Echo JSON through a loop in PHP?

I have a loop that grabs DB values and creates an object. I want to echo a JSON object every time the loop is iterated through. As of now, I just get blank in my console. Also, those commented out printf statements work fine. Any help would be much appreciated!
AJAX call
$.ajax({
url:'ajax/ipGet.php',
type: 'GET',
dataType:'json',
success:function(response){
console.log(response);
}
});
PHP Data Generation
$infoArray = new Array();
while($row = mysqli_fetch_array($getIpQuery, MYSQLI_NUM)){
for($x=0;$x<count($row);$x++)
{
$getIpInfo = mysqli_query($dbcon,"SELECT * FROM ipInfo WHERE address='$row[$x]'");
$retrievedInfo = mysqli_fetch_array($getIpInfo,MYSQLI_NUM);
$ipInfo->ipAddress = $retrievedInfo[0];
$ipInfo->port = $retrievedInfo[1];
$ipInfo->status = getStatus($ipInfo->ipAddress, $ipInfo->port);
array_push($infoArray,$ipInfo);
}
}
echo json_encode($infoArray);
Thanks for any help!
~Carpetfizz
json must be a single self-contained entity. You're outputting MULTIPLE separate bits of JSON text, which is incorrect.
JSON encoding should be the very LAST thing you do, e.g.
while(...) {
$array[] = ....
}
echo json_encode($array);
Consider what you're doing from the client perspective... building an array of ipinfo, so you run the loop once and produce
{"ipAddress":"127.0.0.1","port":80,....}
But you're doing it multple times, so you end up with
{"ipAddress":"127.0.0.1","port":80,....}{"ipAddress":"127.0.0.1","port":80,....{"ipAddress":"127.0.0.1","port":80,....}
as your output, and now you've got illegal javascript. Remember that JSON text is essentialy the right-hand-side of a Javascript assignment operation, e.g.
var somevar = ...json_goes_here...;
So you're doing
var stuff = {...}{...}{...};
which is an outright syntax error, instead of
var stuff = [{...},{...},{...}];
which would be correct.

Categories