Refresh PHP functions with JavaScript - php

i need a a script that will refresh the functions:
$ping, $ms
every 30 seconds, with a timer shown,
i basicly got this script:
window.onload=function(){
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds;
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
}
but it refreshes the whole page, not the functions i want it to refresh, so, any help will be appriciated, thanks!
EDIT:
I forgot to mention that the script has to loop infinatly

This here reloads the whole page:
window.location.reload();
Now what you seem to want to do is reload portions of the page, those portions having been generated by php functions. Unfortunately php is server side so that means you cant get the client browser to run php. Your server runs the php to generate stuff that browsers can understand. In a web browser open a page you made using php and choose to view source and you'll see what I mean.
Here's what you'll need to do:
Make your two functions ping and ms accessable via ajax
Instead of window.location.reload() do a call to jQuery.ajax. on success write to your page
Here's what I think would be the ideal way of dealing with this... I haven't seen the php side of your problem but anyway:
make a file called ping.php and put all your ping function code in there. ditto for ms
in your original php file that called those functions, make a div at each point where you wanted a function call. Give them appropriate ids. Eg: "ping_contents" and "ms_contents"
You can populate these with some initial data if you want.
In your js put in something like this:
jQuery.ajax(
{
url : url_of_ping_function,
data : {anything you need},
type : 'POST', //or 'GET'
dataType: 'html',
success : function(data)
{
document.getElementById("ping_contents").innerHTML = data;
}
});
do another one for the other function

What you want is AJAX, Asynchronous JavaScript and XML
You can use jQuery for that.
I can put an example here, but there is a lot of information to be found on the internet. In the past I wrote my own AJAX code, but since I started using jQuery, it's all a lot easier. Look at the jQuery link I provided. There is some usefull information. This example code might be the easiest to explain.
$.ajax({
url: "test.php"
}).done(function() {
alert("done");
});
A some moment, for example on a click on a button, the file test.php is executed. When it's done, a alert box with the text "done" is shown. That's the basic.

Related

change values in html based on database input

I'm trying to develop an application in which it is very important to detect changes in a database in real time. I have devised a method to detect the changes now by running an ajax function and refreshing the page every 3 seconds, but this is not very efficient at all, and on high stress levels it dosen't seem like an effective solution.
Is there any way I can detect if some change has been made in the database instantly without having to refresh the page? The sample code is attached. I'm using php as my server side language, with html/css as the front end.
$(document).ready(function() {
$('#div-unassigned-request-list').load("atc_unassigned_request_list.php");
$('#div-driver-list').load("atc_driver_list.php");
$('#div-assigned-request-list').load("atc_assigned_request_list.php");
$('#div-live-trip-list').load("atc_live_trip_list.php");
setInterval(function() {
$.ajax({url:"../methods/method_get_current_time.php",success:function(result){
$("#time").html(result);
}});
}, 1000)
setInterval( function() {
$.ajax({url:"atc_unassigned_request_list.php",success:function(result){
$("#div-unassigned-request-list").html(result);
}});
$.ajax({url:"atc_driver_list.php",success:function(result){
$("#div-driver-list").html(result);
}});
$.ajax({url:"atc_assigned_request_list.php",success:function(result){
$("#div-assigned-request-list").html(result);
}});
} ,2000);
});
Please help!
For me, the best solution is
On the server side write a service that identify the changes
On the client, check this service with websockets preferencially (or ajax if you can not use websockets), then if there have changes, download it, This way you have, economy and velocity with more funcionality
Examples Updated
Using ajax
function downloadUpdates(){
setTimeout(function(){
$.ajax({
url: 'have-changes.php'
success:function(response){
if(response == 'yes'){
// ok, let`s download the changes
...
// after download updates let`s start new updates check (after success ajax method of the update code)
downloadUpdates();
}else{
downloadUpdates();
}
}
});
}, 3000);
}
downloadUpdates();
Using websockets
var exampleSocket = new WebSocket("ws://www.example.com/changesServer");
exampleSocket.onmessage = function(event) {
if(event.data != "no"){
// ok here are the changes
$("body").html(event.data);
}
}
exampleSocket.onopen = function (event) {
// testing it
setInterval(function(){
exampleSocket.send("have changes?");
}, 3000)
}
Here (I have tested it ) and Here some examples of how to use websocokets on php, the problem is you will need to have shell access

jQuery Loop that slows your browser

I'm creating online chat, but I'm wondering while using jQuery .load() in my script, my browser seems to get slow. When i checked the inspect element "Net" section, it loads bunches of GET-data... etc.
I would like to know if there's a better script solution with this code to prevent chat being heavy in the background while the data keeps looping in the background to check who's keep coming online/offline.
setInterval('loadThis()', 5000);
function loadThis () {
$("#loads").load('includes/users.php', function(){
$(".chat-side-panel li").each(function(i){
i = i+1;
$(this).addClass("stats"+i);
var status = $(".stats"+i).find("span.bullet").data("status"),
flag = $(".stats"+i).find("span.mail").data("flag");
if(status == 1) {
$(".stats"+i).find("span.bullet").addClass("online");
}
if(flag == 1) {
$(".stats"+i).find("span.mail").addClass("active");
}
});
});
}
the Chat-Side-Panel will be the main panel, and LI will be the listings of users including their status (online/offline) and flag (message received). As for the standard, what can you suggest for the setInterval time loading (if 5sec. is enough) or should i increase it.
Thanks for your input for this.
PS. We're doing this with both PHP/MySQL also.
One issue I see is that you keep re-querying the DOM for the same elements. Get them once, re-use them thereafter:
var load_target = $('#loads');
function loadThis () {
load_target.load('includes/users.php', function () {
load_target.find('.chat-side-panel li').each(function (i) {
var stats_li = $(this),
bullet = stats_li.find('span.bullet'),
mail = stats_li.find('span.mail');
bullet.toggleClass('online', (bullet.data('status') == 1))
mail.toggleClass('active', (mail.data('flag') == 1));
});
});
}
I don't know all of your involved logic or what the rest of your system looks like, so this particular code may not work exactly. It should simply serve as a re-factor done in a vacuum to show what that function could look like if you stopped hitting the DOM so hard.
Also, use of setInterval is not generally recommended. If the load of the remote file takes a while, you could end up calling loadThis() again before a previous one was completed. This would compound your DOM issues if calls to loadThis() began stacking up. Recursive use of setTimeout is preferred in a situation like this. Here is the above code modified to run recursively, and some usage examples below that:
var load_target = $('#loads'),
loadThis = function (start_cycle) {
$.ajax({
url: 'includes/users.php',
dataType: 'html',
type: 'GET',
success: function (response) {
load_target
.html(response)
.find('.chat-side-panel li').each(function (i) {
var stats_li = $(this),
bullet = stats_li.find('span.bullet'),
mail = stats_li.find('span.mail');
bullet.toggleClass('online', (bullet.data('status') == 1))
mail.toggleClass('active', (mail.data('flag') == 1));
});
},
complete: function () {
if (typeof start_cycle !== 'boolean' || start_cycle) {
load_target.data('cycle_timer', setTimeout(loadThis, 5000));
}
}
});
};
//to run once without cycling, call:
loadThis(false);
//to run and start cycling every 5 seconds
loadThis(true);
// OR, since start_cycle is assumed true
loadThis();
//to stop cycling, you would clear the stored timer
clearTimeout(load_target.data('cycle_timer'));
Last years (around 2012) I developed a chat system for a social network, and saw that
Using setInterval issue is when the request is being sent regularly, without waiting or carry about the result of the first requests in the queue. Sometimes the script can not respond and Mozilla or IE asks the user whether he should block or wait for the non-responding script.
I finally decided to use setTimeout instead. Here is what I did (I use $.getJSON so please study the example and how can use load instead)
function loadThis () {
$.getJSON('url').done(function(results){
//--use the results here
//then send another request
setTimeOut(function(){
loadThis();
},5000);
}).fail(function(err){
//console.log(print(err))
setTimeOut(function(){
loadThis();
},1000);
});
}
loadThis();
PS.: I would like to mention that the time depends on our many items are to be retrieved in your users.php file. Maybe you should use the paging tip. Your users.php can then treat url params users.php?page=1&count=100 for the first request, users.php?page=2&count=100 for the second until the results rows number is 0.
EDITS: In addition, I suggest you consider not interacting with the DOM every time. It is important too.

Making two simultaneous AJAX calls to PHP

I have a form which submits an AJAX request to one of my controllers which uploads a file using PHP's curl. I want to show the user the status of that (PHP) upload, so I store the PHP upload progress in a session variable. Meanwhile, the submission of the form also starts a setInterval() which makes a different AJAX request to controller which checks the session variable. My problem is that the second AJAX call seems to only fire once (instead of throughout the upload process) and so instead of progressively updating the progress, it just returns 100 at the end. What am I doing wrong?
Here's my code:
(note: I'm using the jQuery form plugin to assist with the file upload. It also adds some additional callbacks)
<script>
var check_progress = function() {
$.ajax(
{
url : '/media/upload_progress',
success : function(data) {
console.log(data);
},
async : false
}
);
var options = {
beforeSend : function() {
$("#MediaSubmitForm").hide();
$("#MediaSubmitForm").after('<img class="hula-hippo" src="/img/hippo-hula.gif" />');
t = setInterval( check_progress, 500 );
},
success : function(data){
$(".hula-hippo").hide();
$("#MediaSubmitForm").after("<h3>Upload complete!</h3><p>Do <strong>you</strong> want to <a href='#'>create a project</a> of your own?</p>");
window.clearInterval(t);
console.log(data);
}
};
$("#MediaSubmitForm").ajaxForm(options);
</script>
Use setTimeout();. setInterval() executes the code after the time specified and setTimeout() executes the code every time it reaches the specific time.
These question explain well of their difference :)
setTimeout or setInterval?
'setInterval' vs 'setTimeout'
setInterval & setTimeout?
setInterval and setTimeout
JavaScript setInterval and setTimeout
And a search of this on SO will solve your problem :)
It sounds like this is a PHP locking issue. See the first comment in the answer to this question:
jQuery: Making simultaneous ajax requests, is it possible?

Execute php from javascript

I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.

Running a PHP script via Ajax, through a link?

I'm making a fairly simple rating system, and I've got a small problem. When you +1 rate something, I'm trying to run a PHP script which will connect to the database, download the value from it, +1 to that value, and UPDATE the value in the database again.
I don't think reloading the page for a continious rating system would be a very good idea :S
I'm wondering how I can toggle a PHP script with Ajax, so that when you Click an image of a + sign, it runs the PHP add 1 script, and the + button turns in to a tick. I'm crap at ajax, and I'd go for trying jQuery + $.ajax({}); but I've failed 73 attempts. haha.
Anyone willing to give me a hand writing an Ajax script? :DDD
Thanks! :)
If you want someone to click a link which will access your page, let's assume you have this marup:
<a class = 'plusOne' id = 'someIDForYourSQLTable'>+1</a>
The ID is what you are going to pass to your server script so you can update the appropriate row, generally speaking this should be a primary identifier (i.e. Key) for the record that you want to +1.
Here is the jQuery that will send the ajax request to the file: plusOne.php in the same directory as the current page:
$(function() {
$(".plusOne").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "plusOne.php",
success: function(data) {
// Whatever you want to do after the PHP Script returns.
}
});
});
});
The request will send the a URL parameter 'v' which you can access in your PHP script from the $_GET super global array.
html
<img src="plusone.png" rel="some_unique_id" class="rate" />
javscript
$(".rate").click(function() {
var elem = $(this);
$.get('/rate.php?id=' + elem.attr('rel'), function() {
elem.attr('src', 'checked.png').unbind('click');
});
});
and in php
mysql_connect('localhost','db_user','pssword');
mysql_query('UPDATE database_name.table_name SET rating=rating+1 where id=' . mysql_real_escape_string($_GET['id']));
Have a look at xAjax, a library to expose PHP functions/method to client-side JavaScript. xAjax makes things very simple.
For example, you are able to perform several changes in the browser in parallel:
$objResponse = new xajaxResponse();
$objResponse->assign("myInput1","value",$DataFromDatabase);
$objResponse->assign("myInput1","style.color","red");
$objResponse->append("myDiv1","innerHTML",$DataFromDatabase2);
$objResponse->prepend("myDiv2","innerHTML",$DataFromDatabase3);
$objResponse->replace("myDiv3","innerHTML","xajax","<strong>xajax</strong>");
$objResponse->script("var x = prompt("Enter Your Name");");
return $objResponse;

Categories