After a week of googling and search.I am hard to find even a single tutorial about long polling from a database table instead of from a flat text file named data.text. Currently, I write manually anything in data.text and it instantly appears in the browser.
This is the question: Long polling using database? is not answered properly even in StackOverflow. (I found a lot here but in vain.).Example of this is also here
filemtime alternative for MySQL
How can I modify getdata.php to make it enable for fetching data from database?
$sql=mysqli_query($database,"SELECT * FROM messages where time>=$curr_date ORDER by time DESC");
while($row=mysqli_fetch_array($sql)){
$messages=$row['messages'];
$id=$row['id'];
echo $messages;
}
Messages table is as follows
id fro to mesg time status last_modified
I am here listing an example.
In this example, three files are being used.
index.html
getdat.php
data.text
Is there any need to make a fourth file to get data from database(mysql)? if not, then what type of changes are necessary in the getdata.php or data.text to use dynamic data from database?
Here is my Javascript
<script type="text/javascript" charset="utf-8">
var timestamp = null;
function waitformsg() {
$.ajax({
type:"Post",
url:"getdata.php?timestamp="+timestamp,
async:true,
cache:false,
success:function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
$("#messages").append(json['msg']);
}
timestamp = json["timestamp"];
setTimeout("waitformsg()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("waitformsg()", 15000);
}
});
}
$(document).ready(function() {
waitformsg();
});
</script>
Here is the getdata.php file
<?php
include("../model/includes/classes.php");
$filename='data.php';
$lastmodif=isset($_GET['timestamp'])?$_GET['timestamp']:0;
$currentmodif=filemtime($filename);
while($currentmodif<=$lastmodif){
usleep(10000);
clearstatcache();
$currentmodif=filemtime($filename);
}
$response=array();
$response['msg']=file_get_contents($filename);
$response['timestamp']=$currentmodif;
echo json_encode($response);
?>
I have done something very similar recently. I did use jQuery .ajax call instead of the generic XMLhttprequest but the idea is the same:
recentFunction(container, lastDate){
var lastDate = "";
return $.ajax({
type: "POST",
url: "getData.php",
cache: false,
data: { 'request': 'recent',
'param': lastDate },
dataType: "json",
success: function(data){
if(data != null){
$.each(data, function(key, value){
if(key == 0){
lastDate = value['date_added'];
}
var html = "some html here";
// append html to dom element here
// and delete any old items here if needed
});
}
},
complete: function(){
setTimeout(function(){recentFunction(container, lastDate)}, 7000);
}
});
}
in the getData.php file I have query with a where clause that gets any items from db that are more recent than last element. Default value for $lastDate is set to 0, so it returns all items if no date is submitted.
<?php
$lastDate = 0;
$recent = array();
$recentQuery = "SELECT id, date FROM someTable WHERE date > '" . $lastDate . "'";
$recentResults = $db->query($recentQuery);
while($r = $recentResults->fetch_array(MYSQLI_ASSOC)){
$recentMovies[] = $r;
}
echo json_encode($recentMovies);
?>
Related
I am trying to parse the JSON string sent as ajax response from PHP file using jQuery / JavaScript.
Ajax call:
<script>
$(document).ready(function(){
var query = $("#editor").html().replace(/(<([^>]+)>)/ig,"");
$.ajax({
type: "POST",
url: "app/query_db.php",
data: "q="+query,
success: function(resp){
if(resp) {
alert("Response : "+resp);
$("#res_data").html(resp);
}
else{
alert("Response: Failed")
}
});
return false;
});
});
</script>
PHP file :
$db_conn = new db_connect();
$conn = $db_conn->connectToDB($DBHost,$DBName,$DBUser,$DBPwd);
$query_res = array();
if (fill_numeric_array_with_query_assoc($query_res, $sql_query, $conn)) { // Function to execute the query and fill the result
//do nothing
} else {
echo("Error description: " . mysqli_error($conn)); // Error message to display if failed to fetch the data
exit();
}
$data = json_encode($query_res);
echo $data;
Result: [{"uid":"admin","pwd":"xyz"},{"uid":"guest","pwd":"abc"}]
Whenever I try to parse the above JSON string I am ending up with 0 and 1 as keys and the other stuff as values. The strange thing is when I copy this result and assign it to a variable in JavaScript it's parsing the string correctly.
Don't know what's going wrong when trying to parse it as AJAX response.
Table format when parsed the JSON string as AJAX response:
Response when assigned to variable in javascript :
uid pwd
admin xyz
guest abc
This will take the data and turn each object into a row in a table. I'm going to assume that #res_data is an empty <table> element.
$.ajax({
type: "POST",
url: "app/query_db.php",
data: "q=" + query,
dataType: "json",
success: function(resp) {
if (resp) {
alert("Response : " + resp);
$("#res_data").empty();
if (resp.length > 0) {
var header = "<tr>";
for (var key in resp[0]) {
"<th>" + key + "</th>";
}
header += "</tr>";
$("#res_data").append(header);
var rows = "";
for (var i=0; i< resp.length;i++) {
rows += "<tr><td>" + resp[i].uid + "</td><td>" + resp[i].pwd + "</td></tr>";
}
$("#res_data").append(rows);
}
else { alert("No data returned"); }
} else {
alert("Response: Failed")
}
}
});
Note the extra ajax option: dataType: "json". This is important. Because your PHP doesn't send any header to tell the client to interpret the response as JSON, it likely interprets it as text. So you have to add dataType:"json" so jQuery knows what to do, and makes the response directly into a JS object. Then you should have no problem. If you don't, then it will see it as a string, and then loop through it one character at a time, which will result in the strange output you showed in the question.
I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.
You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.
You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"
I have several clones of this script throughout my site and they work. The function is to enable liking, following, etc. (anything that requires a reference table to store the like, follows, etc.) The problem is with my liking function its running the .post 12 times. My follow script has the same jquery code but doesn't do this. So I resorted to checking my fave.php/unfave.php files, but I can't find any errors. Its the same as my follow.php/unfollow.php files. Can anyone spot or realize this odd behavior?
Basically I'm getting 12 entries into my DB. Why?
fave.js
$(document).ready(function(){
$(function(){
$(".fvspan").on("click", ".favebtn", function(){
var fvs = $(this).attr('id');
if(fvs)
{
$.ajax({
type: "POST",
url: "/mobile/inc/vdfave.php",
data: "fvs=" + fvs,
cache: false,
success: function(data){
$("span#" + fvs + ".fvspan").html("<img id='" + fvs + "' class='favebtn-un' src='/assets/faved.png' height='50px'>");
}
});
}
else { }
});
});
$(function(){
$(".fvspan").on("click", ".favebtn-un", function(){
var fvs = $(this).attr('id');
if(fvs)
{
$.ajax({
type: "POST",
url: "/mobile/inc/vdunfave.php",
data: "fvs=" + fvs,
cache: false,
success: function(data){
$("span#" + fvs + ".fvspan").html("<img id='" + fvs + "' class='favebtn' src='/assets/fave.png' height='50px'>");
}
});
}
else { }
});
});
});
vdfave.php
<?php
session_start();
//Make an SQL connection
include('/home/bfreak/www/inc/dbc.php');
$myself = $_SESSION['username'];
$ref = $_POST['fvs'];
$date = date("Y-m-d h:i:s");
if (!isset($_SESSION['loggedIn'])) { }
else{$myinfo = mysql_query("SELECT * FROM users WHERE username = '$myself'");}
while($myid1 = mysql_fetch_array($myinfo))
{
$myid = $myid1['id'];
//Insert form data into database with corresponding structure, in respective order, of SQL columns.
$fvd = "INSERT INTO faves (vid, usr, date) VALUES ('$ref', '$myid', '$date')";
if (!mysql_query($fvd, $con)) {die('Fatal Error: ' . mysql_error());}
}
mysql_close($con);
?>
Make sure you don't have duplicate usernames in users table in database. while loop may be running 12 times.
Change this:
mysql_query("SELECT * FROM users WHERE username = '$myself'");
to following:
mysql_query("SELECT * FROM users WHERE username = '$myself' LIMIT 1");
and check again.
I figured it out! i ran the js script in the loop. I took it out and it works!
I have created a relatively simple "ideas board" in PHP/jQuery/MySQL.
On page load the div #chat pulls the current entries in the database.
<div id="chat">
<?php
$sql = "SELECT * from idea ORDER BY id DESC;";
$result = $pdo->query($sql);
if($result->rowCount() > 0 && !empty($result))
{
foreach ($result as $row)
{
$title = $row['title'];
$idea = $row['idea'];
echo '<span class="idea"><strong>' . $row['title'] . "</strong> - " . $row['idea'] . ' <a class="delete" href="">[Delete]</a></span>';
}
}
?>
</div>
However I'd like it to be refreshed periodically using:
<body onload="setInterval('chat.update()', 1000)">
The below example details how it can be done using a text file, how would I do it with querying a database (the example was found at http://css-tricks.com/jquery-php-chat/)?
//Updates the chat
function updateChat() {
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {'function': 'update','state': state,'file': file},
dataType: "json",
success: function(data) {
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("
"+ data.text[i] +"
"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
}
});
}
else {
setTimeout(updateChat, 1500);
}
}
I expect certain rows to be deleted as well, so on top of entries being appended, I'd also like some to be removed.
It should simulate a real-time conversation.
You can use simple long polling technique to update your chat.
eg:
//Updates the chat
function updateChat() {
if(! instance){
instance = true;
$.ajax({
type: "POST",
url: "process.php",
data: {function: 'update', state: state, file: file},
dataType: "json",
success: function(data) {
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("
"+ data.text[i] +"
"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instance = false;
state = data.state;
},
complete: function(){
setTimeout(
updateChat, /* Request next message */
10000 /* ..after 10 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//display you error message
},
timeout: 10000 //Timeout is necessary to prevent chaining of unsuccessful ajax request
});
}
}
You can use socket.io library to implement server to client notifications and/or real time communication in both directions.
I am writing an app (not web app) for mobile devices using icenium which uses javascript etc rather than its native language.
The app displays rows from a data base, displaying events. The user then clicks on an event which displays more information on the event, however I am having trouble calling the ajax from a js function as below:
function showSingle(itemId){
//document.write(itemId);
$('#output').fadeOut();
$('#single').fadeIn("fast");
$.ajax({
url: 'http://dev.123456789.co.uk/getSingle.php',
dataType: 'jsonp',
data: { dbId: itemId },
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
var linkedPageSingle = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
$('#single').append(linkedPageSingle);
// pageId = $('#pageid').html();
$('#single').text('debugdebug.');
},
error: function(){
$('#single').text('There was an error loading the data.');
}
});
}
This does not return any data, it doesn't even return $('#single').text('debugdebug.'); so there must be a problem with the ajax call? Also
error: function(){
$('#single').text('There was an error loading the data.');
}
Is not outputted. Can you spot an error in this? The call to the function is here:
var linkedPage = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
Which is in a document.ready section of the page, inside an ajax method (which works).
getSingle.php:
<?php
/*
* Script to connect to database and pull out information for app!
*/
include 'connect.php';
$dbId = $_POST['dbId'];
$query = mysql_query("SELECT * FROM calTest where `id`='$dbId'");
$records = array();
while($row = mysql_fetch_assoc($query)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
Can't see where I have gone wrong, Thanks!
I think the problem is with Posting of data
$dbId = $_POST['dbId'];
echo $_GET['jsoncallback'];
you are using the get or post method together
You set the callback to jsoncallback so you need to add that function to parse item:
function showSingle(itemId){
//document.write(itemId);
//$('#output').fadeOut();
//$('#single').fadeIn("fast");
$.ajax({
url: 'http://dev.thedesignworks.co.uk/getSingle.php',
dataType: 'jsonp',
data: { dbId: itemId },
jsonp: 'jsoncallback',
timeout: 5000
});
}
function jsoncallback(data, status) {
var linkedPageSingle;
$.each(data, function(i, item) {
linkedPageSingle = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
$('#single').append(linkedPageSingle);
// pageId = $('#pageid').html();
});
$('#single').text('debugdebug.');
}
Try this
function showSingle(itemId){
//document.write(itemId);
$('#output').fadeOut();
$('#single').fadeIn("fast");
$.ajax({
url: 'http://dev.thedesignworks.co.uk/getSingle.php',
dataType: 'jsonp',
data: { dbId: itemId },
timeout: 5000,
success: function(data, status){
alert(data)
if (data.length > 0) {
var linkedPageSingle = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
$('#single').append(linkedPageSingle);
// pageId = $('#pageid').html();
$('#single').text('debugdebug.');
}
},
error: function(){
$('#single').text('There was an error loading the data.');
}
});
}
The php page will be
<?php
/*
* Script to connect to database and pull out information for app!
*/
include 'connect.php';
$dbId = $_POST['dbId'];
$query = mysql_query("SELECT * FROM calTest where `id`='$dbId'");
$records = array();
while($row = mysql_fetch_assoc($query)) {
$records[] = $row;
}
if (count($records) > 0)
echo json_encode($records);
?>