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>
Related
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.
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).
So I'm having a little issue. I am working on a site and this is the first I have used ajax to post to to a page. I have a form with a submit button and a link on it. When the submit button is pressed everything works but users should be able to click the link to by pass a page but I still need some information posted to that page so I googled ho to post with out a submit button and ajax came up so I figured I'd give it a shot. It seems to not be working. Here is the code that I am using.
$('#chkEndAccDate').click(function(evt){
alert("before ajax");
var totalcost = $('#total_cost').val();
$.ajax({
type: "POST",
url: "http://sandbox.phareconsulting.com/complete_order.php",
`enter code here`data: {cost : totalCost}
});
alert("after ajax");
});
This code also doesn't work when i try it
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://www.sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
alert("post");
});
});
In the php file right now I am simply doing print_r($_POST); but the post array is empty. Can some one please help me out. I think that some of us just don't understand ajax correctly. I thought I did but I am not able to get it to work.
Thank you.
This should be proper syntax:
data: "{'cost':'" + cost+ "'}"
Use this
data:{cost: cost}
for sending the data.
Use this code:
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
});
});
s.d and Thiefmaster have already written the correct syntax, however, it may be a good idea to change the name of your variable so as to avoid confusion.
var totalCost = $('#total_cost').val();
Then use:
data: {cost : totalCost}
Its a good idea to use the jQuery Form Plugin to send ajax forms this will by itself grab the data and send it to the form action url.
This plugin also gives you functions that control the sending process . This is an example :
var bar = $('#progressBar');
var percent = $('#percent');
var status = $('#status');
$('#form-id').ajaxForm({
beforeSend: function() {
//validate the data
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
// draw a progress bar during ajax request
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
}
});
Html for the progress bar :
<div id="progress">
<div id="bar"></div >
<div id="percent">0%</div >
</div>
css :
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
var count=0;
function createOne() {
var divTag = document.createElement("div");
dynamically created div
var br= document.createElement("br");
count++;
divTag.id = "div1"+count;
Id increment +1
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.style.width="430px";
divTag.style.height="35px";
divTag.style.background="olive";
divTag.className = "dynamicDiv";
divTag.innerHTML = "This HTML Div tag created "
+ "using Javascript DOM dynamically.";
document.body.appendChild(divTag);
document.body.appendChild(br);
}
> Need to save in php using Jquery.
<body>
<h1 align="center">
Click it
<input type="button" id="dev" onClick="createOne()" value="GET">
</h1>
</body>
If you are using jQuery then use it. Convert your function to jQuery and use jQuery's ajax functions.
JavaScript
jQuery(function($){
$('#dev').click(function(){ createOne(); });
window.count = 0;
function createOne() {
var new_id = 'div1' + (++count);
$('body').append('<div class="dynamicDiv" id="' + new_id + '" style="margin: 0px auto; width: 430px; height: 35px; background-color: olive;">This HTML Div tag created using Javascript DOM dynamically.</div><br/>');
$.get('/div-id-saver.php', { 'id': new_id }, function(response){
console.log('post response:' + response);
});
}
});
HTML
<body>
<h1>
Click it
<input type="button" id="dev" value="GET">
</h1>
</body>
More info: http://api.jquery.com/category/ajax/shorthand-methods/
In your createOne() function, you can do an AJAX post back to a PHP script passing through the ID of the element you just created.
You can find more information on JQuery's AJAX here
You haven't specified what you want to do with the information or when so this should help to get started.
In the ajax call, the data will look like:
var mydata = new Array ();
$("div[id^='div']").each (function (){
mydata.push ({$(this).attr ("id") : $(this).text ()});
});
I use the text of the div as the value, but you can change it to your needs...
I suggest you post the data by Ajax
createOne = function() {
var $div = $('#div1'+count);
$.ajax({
type: "POST",
url: "some.php",
data: { id: "div1"+count, html: $div.html() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
** Using jQuery **
// Within your createone() function
// Location of your PHP file
var url = 'savemyvar.php';
$.post(url, { div : divTag.id }).success(function(data, status, xhr)
{
// Do something on success
}).error(function(data)
{
// Do something on error
});
Info on $.post a helper function for $.ajax
$.ajax documentation
This will send your divTag object to the PHP script that you can use
$_REQUEST['div']
to access.
I am loading html with javascript from php to a div using $.get() to a div. the button click event is working fine. then adding again same thing again to different div with different id, but it is not working. can anyone can help me. my code is this
<style>
.loadWindow {
width:333px;
height: 202px;
padding: 5px 5px 0 5px;
font: 12px Arial, Helvetica, sans-serif;
border:double;
}
#loadWindow {
display:none;
}
<div id="main-box">
<div class="loadWindow" id="loadWindow"></div><button id="make">make</button>
My javascript code is below
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
`
My mydata.php code is below
echo '<div><button id="closeBtn">Close</button></div><script>$("#closeBtn").click(function(){alert("Close button Clicked!");});</script>';
I want click event work for each window separately(individually) and display the alert. In this code click event is not working according to the window. What can I do?
Working demo http://jsfiddle.net/QYEWs/13/
Please use .on API to it attaches an event handler function for one or more events to the selected elements.
API: http://api.jquery.com/on/
Plz Note: your append will make the DOM invalid as your id will always be same make it a class
to attach click event on dynamically added html in DOM
This should help, :)
like this
Attaché click event to close button like this:
$("#main-box").on("click",".closeBtn", function() {
alert("Close button Clicked!");
});​
$(function(){
$('#make').on('click', function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone(true).attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});