Jquery AJAX get new mysql records in real time - php

Is there any twitter-like solution for retrieving new mysql records using PHP in real-time and having them slide down
Thanks,

Try like this
$(function() {
setInterval(function() {
$.ajax({
type: "GET",
url: "location/of/server/script.php",
success: function(html) {
// html is a string of all output of the server script.
$("#element").html(html);
}
});
}, 5000);
});
It will update on every 5 seconds.
This is only an example script,fadein effects can be added after the sucess .Hope it helps

i would recommend you to read about websockets if you really want real-time updating. otherwise you could use the jquery setInterval.
websockets:
probably the best one
you can find lots of tuts on the web:
results

If you really want real-time, you're going to want the notifications to be "pushed" to the client, not polled. To do this, on the client side you will probably want to use something like HTML5's "event source" to listen for events and update the UI.
On the server side, there isn't any way for mysql to notify PHP of new records, so you would likely want to use some kind of a message queue (like RabbitMQ or ActiveMQ). You would have to modify the code that inserts into your database so that it also notifies your message queue.

Related

jQuery .get() data from JSON formatted data and refreshing some DOM element to display it

I have heard about technologies like socket.io, but it is too advanced for me.
I created PHP file that displayes JSON formatted data in array.
I use the jQuery function .get() with the URL datafile.php to get the string and display it in the pages. I use timer loop for this .get() and it is run every few seconds. This is how I simulate updating texts without refreshing the page.
But I really think if it is the right way of doing this. is there some better approach?
Here is my current script (the highlights classes are only to make little flashing on the element to show that value has been changed):
setInterval(function() {
$('.total-xp .number').addClass('highlighted');
setTimeout(function() {
$('.total-xp .number').removeClass('highlighted');
}, 1500);
$.get("data.php", function(data) {
$(".total-xp .number")
.text(data.total_xp_data)
}, "json");
}, 10000);
Two comments. You should look at socket.io. Socket.ios allows your server to push data updates to subscribed clients when they happen, thereby saving on wasteful polling for updated data from every attached client, this is pretty much accepted practice. I've no personal experience on socket.io however I've use Signal R in .NET for these kind of problems and found it works well.
Second. I would be tempted to return json to your client, then your client can render the data as appropriate. Then if you need another interface to present the data you don't have to write another server side method, or if you need to change your UI you don't need to reploy the server side components.
If your really can't face the effort of socket.io then your solution will work, it will be hard to get anyone to agree it is best practice.

Use AJAX to update page when new row is added to table

I am in the process of learning AJAX, as I need it for a current project. I have a feed which I want to update live when a new row is added to a MYSQL table. I've actually done this with node.js, but unfortunately my clients server can't use NODE, so I am trying to see if it's possible with AJAX.
Thank you for your help!
There isn't any way that i know about where MYSQL or PHP can push updates to a page when it is updated.
The best option would probably be running timer with javascript and check the database periodically to see if there have been any updates,
var refreshId = setInterval(function() { checkforUpdates(lastIndex) }, 10000);
Pass in the last row of your table index to the javascript function and the function makes an ajax call to a PHP that queries the database for any new rows, if any updates returned, add them to the table with javascript.
If you are also looking to check for updated rows, that gets a bit trickier!
You'll need to have the client either contact the server constantly via polling, or use a push technique such as comet or websockets. Otherwise your client has no way to know when new data has arrived.
Comet and websockets allow for the most real-time feel to the process since they actually send the data to the user client (your connected browser) as soon as it is available whereas with polling it's just your browser querying the server on an interval.
Disadvantage is that push techniques and certainly comet which requires a HTTP Keep Alive can be quite heavy on your server, especially for process based servers such as apache, their maximum connections get filled quickly and then held up until disconnect. There are tuning options and modern settings for it but it's not optimal: the problem even has an official name c10k and is one of the reasons you see event based servers gain popularity these days.
its easier to do ajax stuff with jquery
$("#update_charges").live("click",function() {
$.ajax(
{
type: "POST",
url: "phpfile_toadd_updaterecord.php",
data: "passvalue="+$('input_field_name').val(),
success: function(msg)
{
$('#result_div').html(msg); //msg contains any test echoed from //phpfile_toadd_updaterecord.php file
}
});//end $.ajax
}
below can be your html code
<form>
<div id="result_div"></div>
<input type="button" name="update_charges" id="update_charges" />
<input type="hidden" name="input_field_name" id="input_field_name" value="anyvalue_to be passed to php file"/>
</form>
Jquery ajax help page

The overheads of using setInterval to get latest data from database

im creating a messaging feature that gets the latest messages from a database every few seconds, basically this method does a continuous database search in order to display new messages.
example of the code:
function getLatestActivities(){
var ignoreMessagesArr = $("input.activityId").map(function(){ return this.value; }).get().join(",");
var profileId = $("input#userActivityId").val();
$.ajax({
traditional: true,
dataType: "json",
type: "GET", url: "include/process.php",
data:{
getLatestActivity: "true",
toUser: profileId,
ignoreMessages: ignoreMessagesArr
},
success: function(data){
$.each(data, function (i, elem) {
$('.commentMessage').after(elem.value);
});
}
});
}
What I want to know is whether there is a more efficient way of performing this task, i.e. detecting a change in the database instead(???).
It sounds like you want your web app to receive data when it changes in the database, but not necessarily to send data in real time. If two way communication is required then you are looking for Web Sockets which Socket.IO will help you with server side but requires that you run a Node server. There is a Google code project that enables Web Sockets for PHP called PHPWebSocket but, if I remember right, requires that you run it in a separate process (i.e. run it from the command line). So that kind of takes care of the server part, but now you have to worry about the front-end.
Currently only FireFox and Chrome fully support Web Sockets according to CanIUse. For those browsers lacking support you need a polyfill. Here is a list of HTML5 polyfills. So Web Sockets can be sort of a mess to implement, so make sure that's what you want to do.
On the other hand if your webapp only needs to receive data then EventSource (a.k.a. Server Sent Events) is the way to go. The support is better on the front-end and you don't really have to do much on the server. Again, for less than stellar browsers you will need a polyfill, but that pretty much just means IE. See the following sites/tutorials on how to use this feature.
http://my.opera.com/WebApplications/blog/show.dml/438711
http://dsheiko.com/weblog/html5-and-server-sent-events
http://www.html5rocks.com/en/tutorials/eventsource/basics/
If none of that works there are a few options. Constant polling using some kind of repeating structure like setTimeout, long polling (a.k.a. hanging get) where the server leaves the AJAX request open until there is new data, and there's also the infinite iframe trick, or maybe even a Flash plugin that connects to the server to get data.
You might want to look into Socket.IO it's geared toward realtime communications with the server. Then you can design the backend to push data to the client when it's available rather than constantly polling the database for new information from the frontend
HTML5 Web Sockets allows for two way communication between the client and your server...
In my opinion you should request only the last ID inserted in your database and add it as a parameter to to your ajax request.
process.php should handle that ID and if there are other rows to do the search.
like
$query = mysql_query("SELECT `ID` FROM `table` WHERE `ID`>'$lastId'");
$result = mysql_num_rows(); //use that to see if you have new rows.

Check if webpages are reachable with php and refresh it with ajax

At the moment I’ve got one function to check, if a webpage is reachable. I’ll call this function at about 100 times in a while-loop, which means it sometime lasts 5 minutes to check all these 100 webpages.
I never before used ajax but I would think that it would be a good idea to solve this problem with ajax, but I never used ajax before and have no idea, how to start. Could you give me a good hint? Thanks for every answer!
I would use jquery-ajax, makes it simpler.
So put jquery on your site to start.
This is how jquery ajax works:
$.ajax({
type: 'POST',
url: '--LINK TO PHP/ASP...---', // Place the link that has the command
data: dataString, // dataString is a json encode of the data that is sent to the file
dataType : 'json',
beforeSend:function(){
// Before you send the info, do what you want here (ie loading gif...)
},
success:function(data){
// If it is successful, then it will do what you want here.
}
});
I hope this helps.
I would suggest you use JQuery Ajax, easier to implement.
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
From your (somewhat ill-defined) description, I'd say that using AJAX to control the web site verification would be a deeply in-appropriate approach.
Instead, a more sensible approach would be to "batch process" the web site data via the use of a cron triggered PHP cli script.
As such, once you'd inserted the relevant domains into a database table with a "processed" flag set as false, the background script would then:
Scan the database for web pages that aren't marked as checked within your required time period.
Carry out the CURL lookup, etc.
Update the database record accordingly with the current timestamp.
...
To ensure no overlap with an existing executing batch processing script, you should only invoke the php script every five minutes from cron and (within the PHP script itself) check how long the script has been running at the start of the "scan" stage and exit if its been running for four minutes or longer. (You might want to adjust these figures, but hopefully you can see where I'm going with this.)
By using this approach, you'll be able to leave the background script running indefinitely (as it's invoked via cron, it'll automatically start after reboots, etc.) and simply add web pages to the database/review the results of processing, etc. via a separate web front end.
You could of course use AJAX to get a regular summary of the current status from the database for the purposes of client-side display.

Grabbing data from MySQL using PHP realtime?

I am wondering how I would get data from a MySQL database and display it in real time using PHP. Without having to refresh the page. Thanks!
Use AJAX (I suggest using the jQuery library for this), and have your AJAX script (written in PHP) query the MySQL database.
You can use Socket.Io for more Speed ,efficiency and performance for Your Server
http://socket.io/
But you need Node.Js for that
You will have to use javascript. You can use setInterval(function, n) to fire your update calls every n milliseconds, and a library like jQuery to handle the ajax call and updating your page.
Download jQuery or link to a CDN hosted version of jQuery in your page. Then put something like this on your page:
setInterval(function(){
// inside here, set any data that you need to send to the server
var some_serialized_data = jQuery('form.my_form').serialize();
// then fire off an ajax call
jQuery.ajax({
url: '/yourPhpScriptForUpdatingData.php',
success: function(response){
// put some javascript here to do something with the
// data that is returned with a successful ajax response,
// as available in the 'response' param available,
// inside this function, for example:
$('#my_html_element').html(response);
},
data: some_serialized_data
});
}, 1000);
// the '1000' above is the number of milliseconds to wait before running
// the callback again: thus this script will call your server and update
// the page every second.
Read the jquery docs under 'ajax' to understand the jQuery.ajax() call, and read about 'selection' and 'manipulation' if you don't understand how to update the html page with the results from your ajax call.
The other way to continuously update your page is to use a persistent connection, like web sockets (not currently supported across all the common browser platforms) or a comet-style server-push setup. Try googling comet and/or web sockets for more info, but I think the above method is going to be much easier to implement.

Categories