I'm trying to create a drag & drop calendar(Fullcalendar) and saving the new or edited items in a MySQL database.
But I'm having 2 problems at the moment.
First:
I can't drag & drop more then 1 item in the month view:
http://snag.gy/SF9wI.jpg
But if I drag a new one in the Week view ,It works : http://snag.gy/0tW2m.jpg
and if I go back to the Month view the ones I just created in the Week view are still there.
Second:
I'm new in ajax,jquery and I don't really know how to use $_post, so I can save my records in my MySQL database. I tried a few guides but no success.
MySQL database:
name: tblEvent
idEvent INT auto_increment PRIMARY KEY
fiTask INT
fiUser INT
dtStart DATETIME
dtEnd DATETIME
dtUrl VARCHAR(255)
dtAllDay TINYINT(1)
index.php:
<?php
include_once './Includes/functions.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link href='../fullcalendar.css' rel='stylesheet' />
<link href='../fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='../lib/moment.min.js'></script>
<script src='../lib/jquery.min.js'></script>
<script src='../lib/jquery-ui.custom.min.js'></script>
<script src='../fullcalendar.js'></script>
<script src='../lang/de.js'></script>
<script>
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var h = {};
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .fc-event').each(function () {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
slotEventOverlap: false,
eventLimit: true,
droppable: true, // this allows things to be dropped onto the calendar
events: "./event.php",
// Convert the allDay from string to boolean
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
var title = prompt('Event Title:');
var url = prompt('Type Event url, if exits:');
var eventData;
if (title) {
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: './add_event.php',
data: 'title=' + title + '&start=' + start + '&end=' + end + '&url=' + url,
type: "POST",
success: function (json) {
alert('Added Successfully');
}
});
$('#calendar').fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
$('#calendar').fullCalendar('unselect');
},
editable: true,
/*eventDrop: function (event, delta) {
var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: './update_events.php',
data: 'title=' + event.title + '&start=' + start + '&end=' + end + '&id=' + event.id,
type: "POST",
success: function (json) {
alert("Updated Successfully");
}
});
}*/
});
});
</script>
<style>
body {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}
#wrap {
width: 1100px;
margin: 0 auto;
}
#external-events {
float: left;
width: 150px;
padding: 0 10px;
border: 1px solid #ccc;
background: #eee;
text-align: left;
}
#external-events h4 {
font-size: 16px;
margin-top: 0;
padding-top: 1em;
}
#external-events .fc-event {
margin: 10px 0;
cursor: pointer;
}
#external-events p {
margin: 1.5em 0;
font-size: 11px;
color: #666;
}
#external-events p input {
margin: 0;
vertical-align: middle;
}
#calendar {
float: right;
width: 900px;
}
</style>
</head>
<body>
<div id='wrap'>
<div id='external-events'>
<h3>Aufgaben</h3>
<?php
foreach (SelectTask() as $x) {
echo "<div class='fc-event'>" . $x['dtTask'] . "</div>";
}
?>
</div>
<div id='calendar'></div>
<div style='clear:both'></div>
</body>
</html>
event.php:
<?php
// List of events
$json = array();
// Query that retrieves events
$requete = "SELECT * FROM tblEvent";
// connection to the database
try {
$dbc = new PDO('mysql:host=10.140.2.19;dbname=dbcontrol', 'ymartins', 'a15370430x');
} catch (Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $dbc->query($requete) or die(print_r($dbc->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
add_event.php:
<?php
// Values received via ajax
$title = $_POST['title'];
$user = $_POST['user'];
$start = $_POST['start'];
$end = $_POST['end'];
$url = $_POST['url'];
// connection to the database
try {
$dbc = new PDO('mysql:host=10.140.2.19;dbname=dbcontrol', '****', ****);
} catch (Exception $e) {
exit('Unable to connect to database.');
}
// insert the records
$sql = "INSERT INTO tblEvent (dtTitle, dtStart, dtEnd, dtUrl) VALUES (:title, :start, :end, :url)";
$q = $dbc->prepare($sql);
$q->execute(array(':title' => $title, ':start' => $start, ':end' => $end, ':url' => $url));
?>
What am I doing wrong and how can I improve my script?
You may want to expand your question to include exactly what is going wrong/not working?
I see one issue at least:
your AJAX call should look like this:
$.ajax({
url: '/add_event.php',
data: {'title': title, 'start': start ...}
type: "POST",
success: function (json) {
alert('Added Successfully');
}
});
complete the 'data:' line... its a dict, not a GET Url encoded string when using POST.
you may also want to add a failure section to catch errors, or at least print out the value of the 'json' in case your php page throws an error (it will be in that variable of the success callback).
Related
I'm trying to store the user position + size of my jquery-ui dialogs to a mysql db. I tried reading the manual here: https://api.jqueryui.com/1.10/dialog/ and there was no documentation of how to do this. The issue with my code below is $data = json_decode($_POST["data"]); in savelayout.php returns NULL.
Edit: I was able to get the coordinates to store to mysql via PHP post this way, however they're always the same size 3.078125 and 38.453125. alert(JSON.stringify(order)); always outputs the same coordinates as well, despite using var coord = $(this).position();
Edit: Using .draggable works but not .dialog
Edit: Added more broken code. Whatever.
Example dialogue (draggable + resizable):
<script>
$(document).ready(function() {
$("#menu").dialog({
bgiframe: true,
position: {my: 'left <?php echo $menumy; ?>', at: 'left <?php echo $menuat; ?>', of: window},
modal: false,
height: <?php echo $menuheight; ?>,
width: <?php echo $menuwidth; ?>,
dialogClass: 'fixed-dialog',
dragStop: function(e, ui) { saveCoords(ui.offset.top, ui.offset.left); },
resize: function( event, ui ) {
$( this ).dialog( "option",
ui.size.height + " x " + ui.size.width );
$.post("savelayout.php", { menuheight: ui.size.height, menuwidth: ui.size.width } );
}
}).mousemove(function(){
var coord = $(this).position();
$("p:last").text( "left: " + coord.left + ", top: " + coord.top );
}).mouseup(function(){
var coords=[];
var coord = $(this).position();
var item={ coordTop: coord.left, coordLeft: coord.top };
coords.push(item);
var order = { coords: coords };
});
});
function saveCoords(top, left) {
$.post(
"savelayout.php",
JSON.stringify({
coordtop: Math.round(top),
coordleft: Math.round(left)
})
);
}
</script>
Ok, so when you move a dialog, you can do this to capture the top (y) and left (x) values.
function saveCoords(top, left) {
$.post(
"savelayout.php",
JSON.stringify({
coordtop: Math.round(top),
coordleft: Math.round(left)
})
);
}
$("#menu").dialog({
bgiframe: true,
position: {
my: 'left top',
at: 'left top',
of: window
},
modal: false,
dialogClass: 'fixed-dialog',
dragStop: function(e, ui) {
saveCoords(ui.offset.top, ui.offset.left);
}
});
When you go to create the Dialog again, and you want to position it back from your values, use position like so:
<?php
// Collect value from MySQL and enter it into an array
$menu = array("at" => array("top" => 0, "left" => 0));
?>
position: {
my: 'left top',
at: 'left+<?php echo $menu['at']['left']; ?> top+<?php echo $menu['at']['top']; ?>',
of: window
}
You can improve this a little with a check:
position: {
my: 'left top',
at: 'left<?php echo isset($menu['at']['left']) ? '+'.$menu['at']['left'] : ''; ?> top<?php echo isset($menu['at']['top']) ? '+'.$menu['at']['top'] : ''; ?>',
of: window
}
Personally, I would feed it into a globally defined variable.
Here is a working example:
https://jsfiddle.net/Twisty/d9ff1LLu/
HTML
<div id="results" class="ui-widget-content"></div>
<button id="remake">Remake Dialog</button>
<div id="menu" title="menu title"></div>
CSS
#results {
height: 2em;
}
jQuery
var menu = {
at: {
top: 0,
left: 0
}
}
function saveCoords(top, left) {
$.post("/echo/json/", {
json: JSON.stringify({
coordtop: Math.round(top),
coordleft: Math.round(left)
})
}, function(results) {
menu.at.top = results.coordtop;
menu.at.left = results.coordleft;
$("#results").html("Recorded { top: " + results.coordtop + ", left: " + results.coordleft + "}");
});
}
$(document).ready(function() {
$("#remake").button().click(function() {
$("#menu").dialog("close");
$("#menu").remove();
$("#results").html("Removed Menu. Creating new at position: 'top+" + menu.at.top + " left+" + menu.at.left + "'");
var menuDialog = $("<div>", {
id: "menu",
title: "New Menu Title"
}).dialog({
bgiframe: true,
position: {
my: 'left top',
at: 'left' + (menu.at.left > 0 ? "+" + menu.at.left : '') + ' top' + (menu.at.top > 0 ? "+" + menu.at.top : ''),
of: window
},
modal: false,
dialogClass: 'fixed-dialog'
});
});
$("#menu").dialog({
bgiframe: true,
position: {
my: 'left top',
at: 'left top',
of: window
},
modal: false,
dialogClass: 'fixed-dialog',
dragStop: function(e, ui) {
saveCoords(ui.offset.top, ui.offset.left);
}
});
});
I'm having an image map with ajax hover to retrieve information from database table major_occurrence. But it's seems not working at all with the ajax call.
The hover is clickable so that it will redirect to another doRpMap.php showing the occurrence details.
Please advise on this matter. Thanks. *Pardon me being a programming newbie.
Am I doing the correct way for:
the variable to call back getOccCount.php $result in my Main Page?
how to insert the ajax call() into my <span>?
getOccCount.php
<?php
$location_id = $_GET['location_id'];
$query = "SELECT COUNT(occurrence_id) FROM major_occurrence WHERE '$location_id' = location_id GROUP BY location_id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$array = mysql_fetch_row($result); //fetch result
echo json_encode($array);
?>
Main page
<style type="text/css">
#map {
margin:0;
padding:0;
width:950px;
height:1211px;
background:url(images/Campus-Map.jpg);
background-size: 950px 1211px;
font-family:arial, helvetica, sans-serif;
font-size:8pt;
}
#map li {
margin:0;
padding:0;
list-style:none;
}
#map li a {
position:absolute;
display:block;
background:url(blank.gif);
text-decoration:none;
color:#000;
}
#map li a span { display:none; }
#map li a:hover span {
position:relative;
display:block;
width:200px;
left:20px;
top:20px;
border:1px solid #000;
background:#fff;
padding:5px;
filter:alpha(opacity=80);
opacity:0.8;
}
#map a.rpc{
top: 1060px ;
left: 585px;
width: 78px;
height: 65px;
}
</style>
<body>
<script>
$(document).ready(function() {
$('#map span').hover(function () {
var $t = $(this);
var location_id = $t.attr("location_id");
$.ajax({
url: 'getOccCount.php',
data: "{location_id: location_id}",
dataType: 'json',
method: 'GET',
success: function (result) {
$t.html('Total Number of Occurrence: ' + result[0]);
}
}
});
});
</script>
<ul id="map">
<li><a class="rpc" href="doRPMap.php?location_id=1"><span location_id="1"><b>RPC</b></span></a></li>
</ul>
</body>
A complete solution will require some work. Let me give you a few ideas. I apologize for having trouble with formatting ... the {} function here doesn't seem to work properly for me.
As you stated, you want to query the number of incidents for a given location. In your getOccCount.php I don't see any mechanism of passing a location id. It appears that the query always returns ALL occurrences. You probably want to add a line similar to
$location_id = #$_REQUEST['location_id'];
and use that value in a WHERE clause in your query.
The <span> you have in your html doesn't have a location_id attribute:
<span><b>RPC</b></span>
So the line where you try to retrieve that attribute will not find anything:
var location_id = $(this).attr("location_id");
You're doing the same ajax call twice, in two different ways. The whole block starting with $.ajax({ makes a call to getOccCount.php, however, I don't see you doing anything with the data passed to the success callback.
Then again in the success callback function you write $.get("getOccCount.php", ... which essentially does the same call again. This time you're trying to pass the location_id parameter, which we already know is not looked at in getOccCount.php.
Where you are trying to store the result back in the span that the user hovered over you use $('#map>span') as a selector which will store the result in ALL spans.
So, a start to your solution could look like this:
<body>
<script>
$(document).ready(function() {
$('#map span').hover(function () {
var $t = $(this);
var location_id = $t.attr("location_id");
$.ajax({
url: 'getOccCount.php',
data: "{location_id: location_id}",
dataType: 'json',
method: 'GET',
success: function (result) {
$t.html('Total Number of Occurrence: ' + result[0]);
}
});
});
});
</script>
<ul id="map">
<li><a class="rpc" href="doRPMap.php?locID=1"><span location_id="1"><b>RPC</b></span></a></li>
</ul>
</body>
Like I said, a full solution will require more work, especially on passing the location_id into your query. Hope that my ideas will help make progress.
What I am trying to do is is use jQuery/Ajax to make a request to a PHP script and return a status update each time the foreach loop completes. I want to use the output to make a progress bar.
The problem I am having is the jQuery will only update the page once the whole script has completed. Is there a way to force either the jQuery or PHP to output on every loop and not just dump all of it on success function.
jQuery(document).ready(function($) {
$(document).on('click','#fetch-snowfall-data a',function () {
$(this).text('Fetching Snowfall Data...');
$.ajax({
type: "GET",
async: true,
url: "url.php",
data:{},
dataType: "html",
success: function(response){
$("#response_container").append(response);
$('#fetch-snowfall-data a').text('Fetch Snowfall Data');
}
});
return false;
});
});
PHP
foreach ( $results['resorts'] as $resort ) {
//Do all the things here
$count++;
echo $count .'/'. $results['total_rows'];
}
Thanks everyone for all your help. I eventually managed to get this all working properly and will share exactly how I did it for anyone else's future benefit.
There are 3 files that are required - The page you are loading from, the processing script and the listening script.
You will need to know how many rows you are going to process for everything to work. I load mine from php variable $results['total_rows']; in loading.php
Loading.php
jQuery(document).ready(function($) {
setTimeout(getProgress,1000);
$(document).on('click','#fetch-snowfall-data a',function () {
$(this).text('Fetching Snowfall Data...');
$.ajax({
url: 'process.php',
success: function(data) {
$("#response_container2").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'listen.php',
success: function(data) {
if(data<=<?php echo $results['total_rows']; ?> && data>=1){
console.log(data);
$('#response_container').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / <?php echo $results["total_rows"] ?>)*100 +'%">'+ data + '/' +<?php echo $results["total_rows"] ?> +'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#fetch-snowfall-data a').text('Fetch Snowfall Data');
console.log('End');
}
}
});
}
});
Process.php
foreach ( $results['resorts'] as $resort ) {
//Do all the things here you want to.
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = $results['total_rows'];
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
Listen.php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
Some CSS for the progress bar
#progress {
height: 20px;
margin-bottom: 20px;
/* overflow: hidden; */
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
As suggested by adeneo, I dont think you can return partial content. I tried to research on this before with no avail. However, if anyone can correct me, i'll be very appreciative.
The end result for me is to do recursive ajax.
javascript
var data = '';
$(document).on('click','#fetch-snowfall-data a',function () {
ajaxCall(0);
});
function ajaxCall(num) {
$.ajax({
type: "POST",
async: true,
url: "url.php",
data: num,
dataType: "json",
xhr:function(){
//progress bar information here.
},
success: function(response) {
$("#response_container").append(response['data']);
if (response['check'] === 'next') {
var nextNum = num +1;
data += response['data'];
ajaxCall(nextNum); //call itself for the next iteration
}else if (response['check'] === 'done'){
data = response['data'];
//do stuff with the data here.
}else if (response['check'] === 'error') {
return response['data'];
}
},
error:function(xhr, status,error){
//error information here
}
});
}
For PHP:
Just make sure you output stuff in json with two information. Json.check: to see if you want to move into the next iteration, finish and output data, or report error. Json.data to output whatever data it needs. What you need to do is output each report at a time without foreach loop
--edit--
I found some topic on streaming for php
http://www.sitepoint.com/php-streaming-output-buffering-explained/
Best approach for (cross-platform) real-time data streaming in PHP?
I am attempting to create a MySQL backed events interface, using fullCalendar and MySQL. I have tried to manipulate the examples in the fullCalendar documentation and have successfully created a events feed from my database.
I am now trying to create a eventDrop call which sends an events id, title and start time to the database. I used the code from a previous question to create the eventDrop call, here is the JavaScript for the whole callendar page:
$(document).ready(function() {
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// if so, remove the element from the "Draggable Events" list
$(this).remove();
},
// events from mysql database
events: "/json-events.php",
// submit to database
eventDrop: function(calEvent, jsEvent, view) {
var method = 'POST';
var path = 'submit.php';
var params = new Array();
params['id'] = calEvent.id;
params['start'] = calEvent.start;
params['end'] = calEvent.end;
params['title'] = calEvent.title;
post_to_url( path, params, method);
}
});
});
The PHP file I hoped would receive the POST data and insert it into the database with an end time equal to the start time plus 15 mins (edited after answer below):
<?php
mysql_connect("") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$id = $_POST["id"];
$title = $_POST["title"];
$start = $_POST["start"];
$end = date(Y-m-d T H:i:s , strtotime($start)+900);
$query = "INSERT INTO `events` VALUES (`$id`, `$title`, `$start`, `$end`, ``)";
mysql_query($query);
print $query;
?>
The database is not receiving the event data.
This is the conclusion I have come up with and I have no problem running this off my test and public server.
I have taken the FullCalendar and this is the format I use.
The database is real simple.
id integer 11 chars primary key auto-increment,
title varchar 50,
start varchar 50,
end varchar 50,
url varchar 50.
This is the index.php or index.html file.
<!DOCTYPE html>
<html>
<head>
<link href='css/fullcalendar.css' rel='stylesheet' />
<link href='css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='js/jquery-1.9.1.min.js'></script>
<script src='js/jquery-ui-1.10.2.custom.min.js'></script>
<script src='js/fullcalendar.min.js'></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: "json.php",
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
</script>
<style>
body {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}
#loading {
position: absolute;
top: 5px;
right: 5px;
}
#calendar {
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id='loading' style='display:none'>loading...</div>
<div id='calendar'></div>
<p>json.php needs to be running in the same directory.</p>
</body>
</html>
This is the json.php file.
<?php
mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("calendar") or die("Could not select database");
$rs = mysql_query("SELECT * FROM events ORDER BY start ASC");
$arr = array();
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo json_encode($arr);
?>
Once remove the column names in insert query and try, if you don't get then let's think about it. Do something like this
mysql_query(INSERT INTO `events` VALUES ('$id', '$title', '$start', '$end', ''));
Just print the post values before inserting, if it seems clear, then check your query.
echo the query and exit, you may get something like this
mysql_query(INSERT INTO `events` VALUES ('23', 'event title', 'start date', 'end date', ''));
Run this query to find errors if any
print $query - there should be a ; at the end
is there any jQuery plugin to create something like the live feed from the Twitter Main Page , using PHP, which is getting the data from a MySQL database?
How has to be the PHP file?
Thanks.
You really don't need a plugin for this, you could easily create something similar yourself using jQuery to make AJAX calls to a PHP MySQL feed
Create a script to make reoccurring AJAX calls using setTimeout() and then add the new found results to the feed container using .prepend()
HTML
<html>
<head><title>Tweets</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#tweets {
width: 500px;
font-family: Helvetica, Arial, sans-serif;
}
#tweets li {
background-color: #E5EECC;
margin: 2px;
list-style-type: none;
}
.author {
font-weight: bold
}
.date {
font-size: 10px;
}
</style>
<script>
jQuery(document).ready(function() {
setInterval("showNewTweets()", 1000);
});
function showNewTweets() {
$.getJSON("feed.php", null, function(data) {
if (data != null) {
$("#tweets").prepend($("<li><span class=\"author\">" + data.author + "</span> " + data.tweet + "<br /><span class=\"date\">" + data.date + "</span></li>").fadeIn("slow"));
}
});
}
</script>
</head>
<body>
<ul id="tweets"></ul>
</body>
</html>
PHP
<?php
echo json_encode(array( "author" => "someone",
"tweet" => "The time is: " . time(),
"date" => date('l jS \of F Y h:i:s A')));
?>
setInterval() would be more adequate, since you want a check at regular intervals.
Then, there is a jquery comet plugin that explores the implementation of the "push" technology. Check it out here.
var frequency = 5000, // number of milliseconds between updates.
updater = function() {
jQuery.ajax({
url: 'http://twitter.com/example/something.html',
success: function(data) {
// update your page based upon the value of data, e.g.:
jQuery('ul#feed').append('<li>' + data + '</li>');
}
});
},
interval = setInterval(updater, frequency);
<script>
$(document).ready(function(){
var frequency = 10000; // 10 seconds = 10000
var updater = function() {
$.ajax({
url: 'mesaj.html', // data source html php
cache: false,
success: function(data) {
$("#message").html(data); // div id
}
});
};
interval = setInterval(updater, frequency);
});
</script>
example
<div id="message">{ do not write }</div>