RGraph, Multiple Graphs with data from a PHP/MySQL source - php

iam trying to show multiple Graphs in one diagram. The datasource is a MySQL database which is connected via PHP.
My Problem: I cant figure out how to add the data to the RGraph Script. I managed to show one graph via PHP, bt i cant add a seconde one.
This is how i succsessfully get the Data (After connecting to the Database ofc.):
Important!: (At least i guess it is) i have two different cases, in one Case the return Data is a single Number (eg: "2") in my seconde case it is an array of 52 different numbers.
$1 = mysql_query("SELECT * FROM Table WHERE spalte1 ='XX' AND spalte2 ='XX' ORDER BY Datum DESC Limit 1");
if ($1) {
$labels = array();
$data = array();
while ($row = mysql_fetch_assoc($1)) {
$labels[] = $row["datum"];
$2[] = $row["max"];
}
// Now you can aggregate all the data into one string
$2_string = "[" . join(", ", $2) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
}
else
{
print('MySQL query failed with error: ' . mysql_error());
}
This is how i draw the Graph:
<canvas id="cvs" width="1200" height="250">[Browser not supported]</canvas>
<script>
//window.onload = function ()
//{
new RGraph.Line({
id:'cvs',
data:[<?php print($2_string) ?>],
options: {
colors:['#B71A1A'],
backgroundGrid: true,
//xaxisLabels: [<?php print($labels_string) ?>],
//xaxisLabelsAngle: 25,
xaxis: true,
yaxis: true,
yaxisScale: true,
yaxisScaleUnitsPost:'%',
yaxisScaleMax: 100,
title: 'XX',
textAccessible: true,
key: ['XX'],
keyPosition: 'margin',
keyPositionX: 25,
}
}).draw();
But how can i add a seconde graph into this diagram? All the Demos say something like:
data = [[1,2,3],[4,5,6]]
So i tryed different versions (just one example):
data = [[<?php print($1_string) ?>],[<?php print($2_string) ?>]]
Hopefully someone has an Idea ... :)
Thx for every try :)

Here is what I sent Simon via email
<?php
$1_data = 5;
$2_data = array(2,3,8 4,6,8,6,9,8,7,5,8);
// Make JavaScript arrays out of the above number and PHP array
// also making an array of two numbers out of the single number
$1_string = '[' . join(',', array($1_data, $1_data) . ']';
$2_string = '[' . join(',', $2_data) . ']';
?>
<canvas id="cvs" width="1200" height="250">[Browser not supported]</canvas>
<script>
new RGraph.Line({
id:'cvs',
data:[
<?php print($1_string) ?>,
<?php print($2_string) ?>
],
options: {
}
}).draw();
</script>

Related

PHP Traverse through JSON using foreach

I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. I am trying to grab coordinates from google geocoding API and stick them into Places for Web. I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work.
Here is the JSON object from the place search API
{
"html_attributions":[ ],
"results":[
{
"geometry":{ },
"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
"name":"Guadalajara Mexican Grill & Cantina",
"opening_hours":{ },
"photos":[
{
"height":2952,
"html_attributions":[ ],
"photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
"width":5248
}
],
"place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
"price_level":2,
"rating":4.4,
"reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
"scope":"GOOGLE",
"types":[ ],
"vicinity":"105 North Main Street, Lake Elsinore"
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"status":"OK"
}
I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. Here is my attempt at that:
UPDATE
<?php
if(!empty($_GET["location"])){
//$API_key = "";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($_GET['location']) .
'&key=';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
'location=$lat,$lng' .
'&radius=1500' .
'&rankby=distance' .
'&key=';
$places_json = file_get_contents($places_url);
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array as $item) {
var_dump($places_array );
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>What is Here?</title>
</head>
<body>
<h1>Type in a location</h1>
<p>This program will display pictures of places to go in that area</p>
<form action ="">
<input type ="text" name ="location"/>
<button type ="submit">Go!</button>
</form>
<br/>
<?php
echo "$lat $lng";
?>
Just can't seem to get the foreach loop to do anything
the invalid request means wrong url or bad parameters
if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this
"location=$lat,$lng"
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';
you should remove radius or distance you cant get both its on the docs
https://developers.google.com/places/web-service/search?hl=en-419
here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine
after that the foreach should be easy since is only an array look at the code
$thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($thelocation) .
'&key=' . $thekey;
$contextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array["results"] as $item) {
echo $item["name"]."<br>";
}
}
this prints....easy
AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group
The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second.
The json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. More about this.
There's no $item->photo_reference, use:
$results = $places_array["results"];
foreach ($results as $item) {
echo $item["photos"]["photo_reference"];
}

How to remove quotes from each element in a javascript array containing JSON encoded html strings returned from a mysql database with php

Ajax call to the mysql data base using data1.php file with pdo returns hmtl strings that are put into an array, encoded with json and sent to the ajax response function for display in html. Of course the elements in the array have tags and quotations, which are difficult to remove. Easiest and closest solution so far is to replace the quotes in the strings with javascript .replace(). This doesn't work for the array of arrays unless the single element is referenced. What's the way around this? Here is the code.
Ajax call:
function processForm_L(){
var topic = $("#topic").val();
// send data
$.ajax({
url: "../php/get_data1.php",
data: {
topic1:topic},
type: 'POST',
dataType: 'json',
success: processResult_L
}); // end .onclick
}
The response function:
function processResult_L(data, textStatus){
// Required Callback Function
if(data['status']['response'] == 1){
//if(data[0] == 1){
table_1 = [];
table_2 = [];
table_3 = [];
table_1 = data.table['a'].replace( /"/g,"");
table_2 = data.data.replace(/"/g,"");
table_3 = data.table['b'].replace( /"/g,"");
//table_1 = JSON.parse(data.table['a']);
//table_2 = JSON.parse(data.data);
//table_3 = JSON.parse(data.table['b']);
//console.log(table_1);
console.log(table_2);
//console.log(table_3);
}//end if response == 1
else if(data.response == 0){
//var response = data + textStatus;
var table_4 = data.error;
$('#display').html(table_4);
}//end if response==0
}//end process results
The query part of get_data1.php
<?php
$ret_s = Array();//return status
$ret_t = Array();//return table
$ret_d = Array();//return data
$result = Array();
$row_1 = 1;
if(!empty($_POST)){
try{
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
// select everything from the raw_data database
$sql = "SELECT * FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
//set response variable
$ret_s['response'] = 1;
//table header
$ret_t['a'] ="<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>";
//fetch each row from database as html
foreach($result as $row){
$ret_d[$row_1] = "<tr>" ."<td>" . $row['ID'] . "</td>" ."<td>" .
$row['Organization'] . "</td>" ."<td>" . $row['Telephone'] . "</td>" . "<td>" . $row['Email'] . "</td>" ."<td>" . $row['Website'] . "</td>" ."<td>" . $row['Country'] . "</td>" ."<td>" . $row['Region'] . "</td>" ."<td>" . $row['City'] . "</td>" ."<td>" . $row['Street'] . "</td>" ."<td>" . $row['Unit'] . "</td>" ."<td>" . $row['Postal_Code'] . "</td>" ."<td>" . $row['Topic'] . "</td>" ."<td>" . $row['Message'] . "</td>" ."<td>" . $row['ts'] . "</td>" ."</tr>";
$row_1++;
}
// end table tag
$ret_t['b'] = "</table>";
//echo and encode array
echo json_encode(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d),JSON_HEX_QUOT|JSON_HEX_TAG);
// echo json_encode(stripslashes_nested(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d)),JSON_HEX_QUOT|JSON_HEX_TAG);
}//end connect
}//end try
catch (PDOException $e) {
$error16 = '<span class="error_s">Try again another time.</span>';
$error17 = '<span class="error_s">ERROR:' . $e->getMessage();
$ret_s['response'] = 0;
$ret_s['error'] = $error16 . $error17;
echo json_encode($ret_s);
} //end failure
}//end if is !empty($_POST)
?>
Note: this queries a localhost database served through xampp. This isn't all the code but everything works just fine except the following:
1) table_2 = data.data.replace(/"/g,""); returns 'data.data.replace() is not a function, because the array is an object not a string
2) when comment out above line and comment in only console.log(table_1); result in console is:
<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr> So that works.
3) similarly commenting in only console.log(table_3); returns in console:
</table> so that also works.
4) if comment in table_2 = data.data; and enter table_2 into console result is:
undefined
5) tried this code to remove quotes from the array of arrays:
a) putting a function in the js init file for the page:
function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
and using that function on the data array in the data object created by the response callback function (so x = data.data)
result is undefined, and it doesn't work.
JSON.parse(table_1); just runs into a < right away and won't parse, for any of the strings in the data array (table_2 or table 3).
adding JSON_HEX_QUOT | JSON_HEX_TAG didn't work.
Presumably looping through the array data.data with a function and using .replace() and a reg exp to replace quotes with nothing should be the easiest solution. Any tips on how to loop through a json_encoded array of html strings in an array returned in an ajax callback?
Don't replace anything anywhere. The only thing you need is to add htmlspecialchars() when you building the HTML string.
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = '<tr><td>'.htmlspecialchars($r['id'])
.'</td><td>'.htmlspecialchars($r['phone_number'])
.'</td></tr>';
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));
Then, when you receive such JSON, just put it into HTML as it is.
$('table#display').html(received_data.table_rows);
But there is better way to implement this. -- Send only data without markup via JSON and build markup in JS:
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = [
'id' => $r['id'],
'phone_number' => $r['phone_number']
];
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));
And then:
// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
var r = received_data.table_rows[i];
$table.append($('<tr>')
.append($('td').text(r.id))
.append($('td').text(r.phone_number))
);
}
PHP case 0, file called from ajax dropdown selector form submission:
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
include "db_connect_df_test.php";
//switch statement for mysql queries based on dropdown selected
switch($topic_2){
case "Address":
//set response variable
$ret_s['response'] = 0;
// select organization address
$sql = "SELECT IFNULL(ID, '--') AS ID,
IFNULL(Organization, '--') AS Organization,
IFNULL(Contact_Names, '--') AS Contact_Names,
IFNULL(City, '--') City,
IFNULL(Street, '--') AS Street,
IFNULL(Unit, '--') AS Unit,
IFNULL(Postal_Code, '--') AS Postal_Code,
IFNULL(Region, '--') AS Region,
IFNULL(Country, '--') AS Country,
IFNULL(ts, '--') AS ts
FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
// extract table rows
foreach($result as $row){
$ret_d[$row_1] = [
'Id'=> $row['ID'],
'Organization' => $row['Organization'],
'Contact_Names' => $row['Contact_Names'],
'City'=> $row['City'],
'Street'=> $row['Street'],
'Unit' => $row['Unit'],
'Postal_Code' => $row['Postal_Code'],
'Region' => $row['Region'],
'Country'=> $row['Country'],
'Date'=> $row['ts']
];//end load data from data base
$row_1++;
}//end table data as rows
break;
Javascript init file, case 0 section of ajax response function:
function processResult_L(data, textStatus){
// Required Callback Function
//create dom elements for table head and body
//to check variables in dev console remove 'var'(make public)
var $table = $("<table id='display_table'>");
$table.append($('<tbody>'));
//create response array
var response = {};
response = data['status']['response'];
//create row array for building table data
var r = [];
switch(response){
case 0: /*Address case */
// build table header
$table.append($('<tr>')
.append($('<th>').text('ID'))
.append($('<th>').text('Organization'))
.append($('<th>').text('Contact'))
.append($('<th>').text('City'))
.append($('<th>').text('Street'))
.append($('<th>').text('Unit'))
.append($('<th>').text('Post Code'))
.append($('<th>').text('Region'))
.append($('<th>').text('Country'))
.append($('<th>').text('Date')));
// build table content
for(var i = 0; i < data.table_rows.length; i++) {
r[i] = data.table_rows[i];
$table.append($('<tr>')
.append($('<td>').text(r[i].Id))
.append($('<td>').text(r[i].Organization))
.append($('<td>').text(r[i].Contact_Names))
.append($('<td>').text(r[i].City))
.append($('<td>').text(r[i].Street))
.append($('<td>').text(r[i].Unit))
.append($('<td>').text(r[i].Postal_Code))
.append($('<td>').text(r[i].Region))
.append($('<td>').text(r[i].Country))
.append($('<td>').text(r[i].Date))
); // end append table content
} // end build table content
break;

How to append the two lines string in php json response

{
"employees": [{
"name": "Chicken Shawarma",
"price": "510.00",
"nutrients": "A
B "
}]
}
this is the my json response , In My app i setup a two line record for "nutrients". Ex :
A
B
this vale saved in database without any issue (My SQL), now i want display the "nutrients" data as a two line record. but its displaying below error
SyntaxError: unterminated string literal
if you have any idea please share with me.
this is the my server side code
if ($itemInfo->num_rows() == 1) {
$row = $itemInfo->row_array();
$json_arr = $_GET['callback'] . '(' .
"{'name' : '" . $row['name'] . "',"
. "'nutrients' : '" . $row['nutrients'] . "',"
. "'img' : '" . $row['img'] . "'}" . ')';
} else {
$json_arr = json_encode(array('status' => 'N'));
}
echo $json_arr;
this is the my client side code
$http.jsonp(full_url).success(function (data) {
$scope.item = data ;
});
Your main problem is making a JSON response by concatenating strings. In such case you miss required encodings/escaping and so on. So, first of all you should create an associative array and then do $json_arr = $_GET['callback'].'('.json_encode($your_json_like_array).')'; exactly like in the else clause.
Resulting code should look like this:
$json_arr = array(
'name' => $row['name'],
...,
'nutrients' => $row['nutrients']
);
$json_arr = $_GET['callback'].'('.json_encode($json_arr).')';

Single jQuery to update multiple elements

I have the following jquery statement:
$("#add").click(
function(event){
var groupName = $("#groupName option:selected").text();
var studentsToAdd = $('select#mainList').val();
var mode = "exempt";
$.post(
"addToList.php",
{ studentsToAdd: studentsToAdd, mode: mode },
function(data) {
$('#groupList').html(data[exemptList]);
$('#mainList').html(data[nonexemptList]);
}
);
});
With the following php code:
$studentsToAdd = $_REQUEST['studentsToAdd'];
$arrayLength = count($studentsToAdd);
$exemptList = "";
$nonexemptList = "";
for ($i=0;$i<$arrayLength;$i++){
$result = mysql_query("UPDATE students SET exempt=1 WHERE id = '$studentsToAdd[$i]'");
}
$result = mysql_query("SELECT * from students WHERE exempt = 1");
while($row = mysql_fetch_array($result))
{
$exemptList = $exemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$result = mysql_query("SELECT * from students WHERE exempt = 0");
while($row = mysql_fetch_array($result))
{
$nonexemptList = $nonexemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$data = array(
'exemptList' => $exemptList,
'nonexemptList' => $nonexemptList
);
echo json_encode($data);
I am trying to update both mainList and exemptList select elements with the single jQuery .post. It is not working. Thoughts?
If your php code is in another page or in a function, which you haven't mentioned, return $data instead of return json_encode($data) should work and leave it as an array. Otherwise you are getting a json string back, from json_encode(), which you need to parse into a javascript object, so try:
var decoded = $.parseJSON(data);
$('#groupList').html(decoded.exemptList);
$('#mainList').html(decoded.nonexemptList);
At least from what i can tell at first glance and 11 pm.
Edit: You can always try console.log(data) with Firefox Firebug plugin and see what you are getting from the server and then see if you need to decode what you are getting, change how you write the array or quotes or whatever.
A possible solution is to decode the JSON object when it is returned. Additionally, the stuff inside the [] needs to have quotes around it:
function(data) {
var json = JSON.parse(data);
$('#groupList').html(json["exemptList"]);
$('#mainList').html(json["nonexemptList"]);
}
Also, maybe try $.ajax, and set dataType to json (even though the default is intelligent guess, which should work anyway since the PHP is sending a JSON object.)
Maybe you could try:
function(data) {
$('#groupList').html(data["exemptList"]);
$('#mainList').html(data["nonexemptList"]);
}
exemptList and nonexemptList were probably treated as variables instead of names.

AJAX PHP MicroBlog Update feed

I'm stuck on my project for college, I've been working on a small time microblog, this may seem silly but I have no idea on how to make the feed auto refresh without killing my monthly bandwidth, here is the code I'm using atm,
Data.php
<?php
// connect to the database
require_once 'script/login.php';
//show results
$query = "SELECT post, PID, fbpic, fbname, fblink, post_date, DATE_FORMAT(post_date, 'Posted on %D %M %Y at %H:%i') AS pd FROM `posts` WHERE 1\n"
. "ORDER BY `post_date` DESC LIMIT 0, 30 ";
$result = #mysql_query ($query);
if ($result) { //If it ran ok display the records
echo '<div id="feed">';
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo '<a name="' . $row['PID'] . '"></a><div id="postsint"><a target="_blank" href="http://www.facebook.com/' . $row['fblink'] . '"><img id="dp" title="' . $row['fbname'] . '" src="https://graph.facebook.com/' . $row['fbpic'] . '/picture"/></a><div id="posttext">' . base64_decode($row['post']) . '<blockquote>' . $row['pd'] . '</blockquote>Share</div></div><br />';
};
echo '</div>';
mysql_free_result ($result);
} else { //if it did not run ok
echo '<h2 id="error">Wisprs could not be retrieved. We apologise for any inconvienience.</h2>'; //public message
echo '<p id="error">' . mysql_error() . '<br /><br /> Query: ' . $query . '</p>'; //debugging message
}
mysql_close(); // Close database connection
?>
content.php
<div id="postlist"> FEED GOES HERE.</div>
All im trying to do is check for updates every 2 seconds and if there is updates then show them in #postlist
It's been a 3 week struggle and I don't know any JavaScript, it's annoying me and I just want to finish this project so I can go to University and maybe learn to do this myself =/
Cheers in advance.
PS - I'm only guessing that it's Ajax but my tutor recommended this site for an answer if I get stuck
Hopefully you are allowed to use jQuery.
Add to content.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function getFeed(){
$.post('Data.php',function(data){
$("#postlist").html(data);
});
setTimeout("getFeed();",2000);
}
window.onload = getFeed();
</script>
getFeed() is called on page load, then calls itself every 2000 milliseconds and appends the data received from Data.php into your postlist element.
This is brute forcing it, making it constantly delete the old html in the postlist div and create all new html every 2 seconds. If you have images that you are loading you will need a more complex solution.
If you use KnockoutJS and jQuery, this might be a good starting point:
http://jquery.com/
http://knockoutjs.com/
content.php
<script type="text/javascript">
$(function() {
// Define our view model that we will feed to KnockoutJS.
var viewModel = {
posts: []
};
// We'll use this variable to keep track of the last post we
// received. When we send our GET request, our php script will be
// able to see $_GET['last_post_date'] and only return the posts
// that come after that.
var last_post_date = null;
// This is the function that will get called every 2 seconds to
// load new data.
var getData = function() {
$.ajax({
url: "/data.php",
data: {
last_post_date: last_post_date
}
}).done( function( data ) {
// We'll assume data.php will give us a JSON object that looks
// like: { posts: [] }
// Append the new posts to the end of our 'posts' array in our
// view model.
viewModel.posts.concat( data.posts );
// Tell KnockoutJS to update the html.
ko.applyBindings( viewModel );
// Store the date of the last post to use in our next ajax call.
last_post_date = viewModel.posts[ viewModel.posts.length - 1 ].post_date;
});
// In 2 seconds, call this function again.
setTimeout( getData, 2000 );
};
// grab the first set of posts and start looping
getData();
});
</script>
<!-- We're telling KnockoutJS that for each 'row' in our 'posts' array, apply
the template named 'row-template'. -->
<div id="postlist"
data-bind="template: { name: 'row-template', foreach: posts }"></div>
<!-- This is the KnockoutJS template that we referenced earlier. Of course,
you don't have to use KnockoutJS to do this. There are plenty of other ways
to do this. Do keep in mind that you'll minimize your bandwidth usage if you
send JSON and use an HTML template rather than loading the same HTML over
and over again. -->
<script type="text/html" id="row-template">
<a data-bind="attr: {name: PID}"></a>
<div id="postsint">
<a target="_blank" data-bind="
attr: {
href: 'http://www.facebook.com/' + fblink
}
">
<img id="dp" data-bind="
attr: {
title: fbname,
src: 'https://graph.facebook.com/' + fbpic + '/picture'
}
" />
</a>
<div id="posttext">
<!--ko text: post--><!--/ko-->
<blockquote data-bind="text: pd"></blockquote>
<a data-bind="
attr: {
href: 'https://www.facebook.com/dialog/feed?' +
'app_id=505747259483458&' +
'link=http://www.wisp-r.com/share.php?' +
'id=' + PID + '&' +
'picture=http://www.wisp-r.com/images/app-icon.png&' +
'name=Wispr by ' + fbname + '&' +
'caption=' + pd + '&' +
'description=' + post + '&' +
'redirect_uri=http://www.wisp-r.com/share.php?id=' + PID
}
">
Share
</a>
</div>
</div>
<br />
</script>
data.php
<?php
// ... do sql stuff ...
// Remember to add a WHERE statement to filter out posts that are earlier than
// or equal to $_GET['last_post_date'].
$posts = array();
if ( $result ) {
while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
array_push( $posts, $row );
}
}
echo json_encode( array( 'posts' => $posts ) );

Categories