how to loop all data on JSON - javascript

Hi I tried Looping my json_encode() to get all data that are related based on my query
the script is working fine but not the looping part
here's what I have so far:
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_GET['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_GET['name'];
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
echo json_encode($message_array);
}
}
It only returns one data from my database..
this is my javascript for retrieving from my php side:
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}

You just keep overwriting $json_string with each loop iteration.
What you want to do is save your DB data to array then encode.
$array = array();
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$array[] = $message_array;
}
}
$json_string = json_encode($array);
echo $json_string;
It also appears that in your AJAX success handler function, you are not properly iterating the array.
Notice here that you only call $.each() on the first array element of the returned result set:
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
I would think you would want to iterate the entire result set like this:
$.each(result, function(rowKey, row) {
// row is single row of result set from database
// rowKey is numerical index of the row in the result set
// rowKey is probably not useful here
// You can just append new div to #clog with
// whatever content from row which you desire
// for example, this would insert message_content value
// in child div to #clog
$("#clog").append('<div>' + row.message_content + '</div>');
});

Try This.....
$i=0;
$fet=mysql_query('select * from tbl1 WHERE tbl1.id='20');
while($row=mysql_fetch_assoc($fet,MYSQL_ASSOC)){
$json[$i]['date']=$row['time'];
$i++;
}
echo json_encode($json);

Please use ->rowCount() to count rows:
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
}
echo json_encode($json);
You should use an array to store your message_arrays, so that you're not just replacing the same variable over and over.

Related

Multiple sets of data insert at one call into separate divs by unique id AJAX

Currently when asking the server for data, when one single set is sent back like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
the div is inserted.
But lets say there's two sets with different notification id's like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
{"num":1,"notification_id":"819","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
Nothing happens
So I'll cut the code down as to show and example of what I have
success: function(response){
if(response.notification_id > notification_id){
$("#notif_ui"+ notification_id).prepend('
<div class="notif_text"><div id="notif_actual_text-'+response['notification_id']+'"
class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+response
['notification_triggeredby']+'.jpg\"
onerror=this.src=\"userimages/no_profile_img.jpeg\"
width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+response.num));
}
I was toying with the idea of maybe using
$.each(response, function (i, val)
But I'm still unsure.
EDIT
Exact response how it shows
{"num":1,"notification_id":"823","notification_content":"Lucy Botham posted a status on your wall","notification_throughurl"
:"singlepoststreamitem.php?streamitem_id=703","notification_triggeredby":"85","notification_status":"1"
,"notification_time":"2015-11-08 04:16:26"}{"num":1,"notification_id":"824","notification_content":"Lucy
Botham posted a status on your wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id
=704","notification_triggeredby":"85","notification_status":"1","notification_time":"2015-11-08 04:16
:27"}
AND MY WHILE LOOP
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
$json['notification_time'] = $row['notification_time'];
echo json_encode($json);
}}
First you need to build an array of notifications, rather than a single one:
<?php
$json = array(
'notifications' => array()
);
while ($row = mysqli_fetch_assoc($com)) {
if ($row['notification_status'] == 1) {
$num = mysqli_num_rows($com);
$notification = array();
if ($num) {
$notification['num'] = 1;
} else {
$notification['num'] = 0;
}
$notification['notification_id'] = $row['notification_id'];
$notification['notification_content'] = $row['notification_content'];
$notification['notification_throughurl'] = $row['notification_throughurl'];
$notification['notification_triggeredby'] = $row['notification_triggeredby'];
$notification['notification_status'] = $row['notification_status'];
$notification['notification_time'] = $row['notification_time'];
$json['notifications'][] = $notification;
}
}
echo json_encode($json);
?>
Then you can access the notifications array from JavaScript:
success: function(response) {
$.each(response.notifications, function(i, notification) {
if (notification.notification_id > notification_id) {
$("#notif_ui" + notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-' + notification['notification_id'] + '" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped' + notification['notification_triggeredby'] + '.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text());
$("#mes").text((i + response.num));
}
})
}
Note, completely untested, but hopefully you can see the difference!
Your php could be changed to
// you can just the the number of rows once outside the while loop
$num = mysqli_num_rows($com);
if($num){
$jsonNum = 1;
}else{
$jsonNum = 0;
}
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){ // this would be unnecessary if you add it as a where conditional to your sql query
// add the num to the array to match your current data structure
$row['num'] = $jsonNum;
$json[] = $row;
}
}
echo json_encode($json);

Why my php array return only recent/last post activities

I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json_encode for append it.
Jquery sent two type data to php file:
1st: page id
2nd: post ids (a jquery array sent them to php file)
If I used print_r($_REQUEST['CID']); exit; on php file for test what he get from jquery, Its return and display all post ids well.
But if I make any reply on particular post, Its only return recent post reply.
That means, if I have 3 post like: post-1st, post-2nd, post-3rd ; my php return only post-3rd activities.
I want my script update any post reply when it submitted at sql.
my wall.php
// id is dynamic
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
//Check for any update after 15 second interval by post id.
<script type="text/javascript" charset="utf-8">
var CID = [];
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep(){
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid : tutid,
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}
$(document).ready(function(){
waitForRep();
});
</script>
server.php (may be problem in my array or something else)
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
} // array close
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows);
$data = array();
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
Try to declare CID array like this:
var CID = new Array();
It looks like you're looping through the CIDs and running an SQL query for each one, but you're only retrieving the results once, outside of the loop. You'll only get the last query's results if you run
$rows = mysqli_fetch_assoc($res);
outside of the CIDs foreach loop.
#koc:
Unfortunately, it won't be as simple as moving the closing loop bracket. If you're trying to retrieve multiple datasets in one AJAX call, then you'll need to handle multiple datasets in your AJAX's success callback, or in your addrep() function. Here's one way to do it, but you can do it many different ways depending on what you're ultimately trying to do:
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
$data = array();
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"
SELECT *
FROM comments_reply
WHERE post_id =".$value."
AND qazi_id=".$_REQUEST['tutid']."
AND date >= '$datetime'
ORDER BY id DESC LIMIT 1
") or die(mysqli_error($dbh));
$row = mysqli_fetch_assoc($res)
$data[] = array_map('utf8_encode', $row);
} // array close
//$rows = mysqli_fetch_assoc($res);
//$row[] = array_map('utf8_encode', $rows);
//$data = array();
//$data['id'] = $rows['id'];
//$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
then in your Javascript:
...
success: function(data){
for (var i=0, len=data.length; i<len; i++) {
addrep("postreply", data[i]);
}
setTimeout(waitForRep, 15000);
},
...
But again, that's just an example. I don't really know what your datasets look like or how you want the data to be passed around and used. This is just an idea that hopefully gets you going in the right direction.

Have any other way in php to stop return undefined value for json_encode

I am sent many dynamic post ids from a page and a php server side page(server.php) make a query with those id to find out newly added data in mysql.
If it not found any newly added data in mysql, it's return a undefined value. So I added this if (msg.id !== undefined && msg.detail !== undefined && msg.name !== undefined) { //do here } to hide undefined.
But after added the above line, my script hide undefined value well but return only for 1st CID's newly added value.
That means If CID sent ids(100, 101, 102, 103 ect.) to php, It's return only 100 id's newly added value and append it.
So without use above method, Have any others way to php server side to remove undefined values?
N.B. Without above line its returned all CID's value well but return also undefined value a time interval if no newly added data found, So I need to stop return undefined.
my javascript:
var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
if (msg.id !== undefined && msg.detail !== undefined && msg.name !== undefined) {
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='newkochi'>"+ msg.name +"</div><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
}
});
}
function waitForRep(){
$.ajax({
type: "GET",
url: "server.php",
cache: false,
data: {CID : CID},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(waitForRep, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForRep, 15000); }
});
}
$(document).ready(function(){
waitForRep();
});
server.php
while (true) {
if($_GET['CID']){ //cid got all dynamic post id as: 1,2,3,4 etc.
foreach($_GET['CID'] as $key => $value){
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_GET['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$data = array();
while($rows = mysqli_fetch_assoc($res)){
$data[]=$rows;
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
$data['username'] = $rows['username'];
$data['description'] = $rows['description'];
$data['date'] = $rows['date'];
//etc. all
$id = $rows['id'];
$qazi_id = $rows['qazi_id'];
$username = $rows['username'];
$description = $rows['description'];
//etc. all
} //while close
} //foreach close
$name .='<p class="name">'.$username.' Says:</p>';
$detail .=''.$description.'';
$data['name'] = $name;
$data['detail'] = $detail;
// do others something more like as above
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} //request close
sleep(5);
} //while close
You're overwriting your values
while($rows = mysqli_fetch_assoc($res)){
$data[] = $rows;
}
That's all you should need to do to populate $data. $data[]=$rows; is telling PHP to append $rows to the array $data. If you need to change data, edit $rows before you do the append.

How to save my jquery array to php using ajax

I have a script that gets the contents of a table that i added.
And i want to do is save the content into a database.
In the picture the table and the content of my dataSet variable that i get from the table.
i check the dataSet and alert it to check if it has value.
My problem is im having trouble saving the array that i passed to php cause its not working its not saving. I got an error in my saveTable.php invalid argument foreach.
script:
var names = [].map.call($("#myTable2 thead th"), function (th) {
return $(th).text();
});
var x = [].map.call($("#myTable2 tbody tr"), function (tr) {
return [].reduce.call(tr.cells, function (p, td, i) {
p[names[i]] = $(td).text();
return p;
}, {});
});
var dataSet = JSON.stringify(x);
alert(dataSet);
$.ajax(
{
url: "saveTable.php",
type: "POST",
data: { tableArray: dataSet},
success: function (result) {
}
});
saveTable.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tableArray = isset($_REQUEST['tableArray']) ? $_REQUEST['tableArray'] : "";
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
$sth = $dbc->prepare($sql);
foreach( $tableArray As $v){
$sth->bindValue(':name', $v[0], PDO::PARAM_STR);
$sth->bindValue(':age', $v[1], PDO::PARAM_STR);
$sth->bindValue(':gender', $v[2], PDO::PARAM_STR);
$sth->bindValue(':action', $v[3], PDO::PARAM_STR);
$sth->execute();
}
?>
new error:
It looks that you are trying to use a String type in the foreach loop. Try:
$tableArray = isset($_REQUEST['tableArray']) ? json_decode($_REQUEST['tableArray']) : array();
This should make it work. Good luck, hope this helps!
You have to convert the string to an array using json_decode to be able to use it as an array.

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Categories