Ajax + PHP?

  • nzk
  • Student
  • Student
  • User avatar
  • Joined: Sep 27, 2006
  • Posts: 77
  • Loc: NY
  • Status: Offline

Post October 19th, 2006, 6:21 pm

I have a php function that outputs the # of pageviews my site has. I dont feel like reloading every. single. time. i want to check (which is as webmasters know, every 2 seconds)

I want to just write/get an ajax script that updates the functions outputs without reloading.

Is there a way for it to not do anything, unless there is a change in the number?

after all that i'd like to add script.aculo.us effects.

Can anyone help? Nothing on the internet helped me at all.
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post October 19th, 2006, 6:21 pm

  • krismeister
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Oct 21, 2006
  • Posts: 202
  • Status: Offline

Post November 1st, 2006, 8:57 pm

the simplest method is to make a page(page #1) which just returns the number of visitors. It should litterally return a page which is:
Code: [ Download ] [ Select ]
21548


On your main page put a span with an ID around your vistor number something like:
Code: [ Download ] [ Select ]
<p>my count is<span id="visitorCount">21544</span> vistors</p>


then make an XMLHttpRequest which returns page #1 above. Then grab the the span by getElementByID("visitorCount") then use innerText() to put the returned value into the span.
  • gisele
  • Expert
  • Expert
  • User avatar
  • Joined: Nov 11, 2004
  • Posts: 579
  • Loc: Nimes (France)
  • Status: Offline

Post November 2nd, 2006, 12:56 am

Hi, I'm agree with Krismeister, I will just add you could trigger the local javascript (yeah pleonasm :-) ) function with a timer
____________________
My web site[/url] oh sh..!
  • krismeister
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Oct 21, 2006
  • Posts: 202
  • Status: Offline

Post November 2nd, 2006, 5:22 am

You mention you want to display scriptaculous effect on change

write an if statement before updating the value that says
Code: [ Download ] [ Select ]
if (elementsCurrentValue != returnedValue){
  //make the innerText update
  //then
  //activate the scriptaculous effect
}
  1. if (elementsCurrentValue != returnedValue){
  2.   //make the innerText update
  3.   //then
  4.   //activate the scriptaculous effect
  5. }


else do nothing.
  • nzk
  • Student
  • Student
  • User avatar
  • Joined: Sep 27, 2006
  • Posts: 77
  • Loc: NY
  • Status: Offline

Post November 2nd, 2006, 8:36 pm

should i make that in an xml file, an html file, or a php file?
  • gisele
  • Expert
  • Expert
  • User avatar
  • Joined: Nov 11, 2004
  • Posts: 579
  • Loc: Nimes (France)
  • Status: Offline

Post November 3rd, 2006, 12:16 am

Hi,

in this case, no need xml file.
first you have to trigger the call to the javascript function with some event (timer, click whatelse)

in your Javascript function(s) you build your XMLHttpRequest object, that'll call the remote procedure. for example a PHP file called rpc.php.

In this script, you get the new value and just echo it.
So this new value will be send back to the client (to the js function that called the remote script).
then in you javascript function you take the responseText of your xmlHTTPrequest object, and give it to the innerHTML propertiy of you span or div and that will update the display.

The main thing is in Javascript catching an event, making an http request to the remote PHP script, and use the response once the remote procedure has been done.
____________________
My web site[/url] oh sh..!
  • nzk
  • Student
  • Student
  • User avatar
  • Joined: Sep 27, 2006
  • Posts: 77
  • Loc: NY
  • Status: Offline

Post November 3rd, 2006, 1:09 pm

Veeeeeeeery Confusing. Since I dont know a line of AJAX. anyways, for some ungodly reason it wont work outputting just the pageviews to a page. any other ways?
  • gisele
  • Expert
  • Expert
  • User avatar
  • Joined: Nov 11, 2004
  • Posts: 579
  • Loc: Nimes (France)
  • Status: Offline

Post November 3rd, 2006, 2:05 pm

HI,
Ajax is not a language, if you know Javascript and any server language (php, asp), you can do some Ajax.

It is really worth looking what does it look like.
Once you've seen it, you like it and need it :-)
Ajax is part of he latest techologies that will be used with web2.0.

here's an example of pseudo Ajax (in fact I'm not using a XML flow back from the remote php script but some simple html ).
I created it as a generic association javascript / php that can update a part of a page inside div tags.
You just have to give an id for the div, in order to pass it as a parameter to the javascript function update_div().

define this on local javscript , the function that do the query to the server and update the div with the html result (responsetext).
It takes 2 parameters, the names of the php function that'll return the new value, and the id of the div to update, see it call the php script rpc.php :

Code: [ Download ] [ Select ]
function update_div(f, object_id)
{
    var ajax = null;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
    {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        ajax = new XMLHttpRequest();
    }
    if(!ajax)
        alert('blemme pas d ajax');
        /*call the remote script with the right name of the function and the div id as GET parameters*/
    ajax.open('get', 'http://your_domain/your_path/rpc.php?object_id=' + object_id + '&f=' + f);
    ajax.onreadystatechange = function()
    {
        if(ajax.readyState == 4)
        {
            //alert(document.getElementById(object_id).innerHTML);
            //alert(ajax.responseText);
            document.getElementById(object_id).innerHTML = '';
            document.getElementById(object_id).innerHTML = ajax.responseText;
            //alert(document.getElementById(object_id).innerHTML);
        }
    }
    ajax.send(null);
}
  1. function update_div(f, object_id)
  2. {
  3.     var ajax = null;
  4.     var browser = navigator.appName;
  5.     if(browser == "Microsoft Internet Explorer")
  6.     {
  7.         ajax = new ActiveXObject("Microsoft.XMLHTTP");
  8.     }
  9.     else
  10.     {
  11.         ajax = new XMLHttpRequest();
  12.     }
  13.     if(!ajax)
  14.         alert('blemme pas d ajax');
  15.         /*call the remote script with the right name of the function and the div id as GET parameters*/
  16.     ajax.open('get', 'http://your_domain/your_path/rpc.php?object_id=' + object_id + '&f=' + f);
  17.     ajax.onreadystatechange = function()
  18.     {
  19.         if(ajax.readyState == 4)
  20.         {
  21.             //alert(document.getElementById(object_id).innerHTML);
  22.             //alert(ajax.responseText);
  23.             document.getElementById(object_id).innerHTML = '';
  24.             document.getElementById(object_id).innerHTML = ajax.responseText;
  25.             //alert(document.getElementById(object_id).innerHTML);
  26.         }
  27.     }
  28.     ajax.send(null);
  29. }


and then you define the function in a php file that'll return the new value, in order to reload only inside the div.


rpc.php :
PHP Code: [ Download ] [ Select ]
 
//don't forget the connexion to DB
 
function new_nb_visit()
 
{
 
   $q = "select new nb_visit from blabla...";
 
   $r = mysql_query($q)or mail("your mail in ", $_SERVER["PHP_SELF"], mysql_error()."\n".$q);//mail if the server is set to do so, otherwise you can die().
 
   $d = mysql_fetch_row($r);
 
   echo $d[0];//echo just the new value or some special displaying of this new value that will replace inside the div
 
}
 
/*in fact, in rpc.php do a dynamic call of he function so that you can use this little association for any div to update with anything to display in : */
 
$fonction = $_GET["f"];
 
$fonction();
 
/*I call the  right function thanks to the name passed to the httpquery inside the javascript function, the one that will send what I want to be displayed*/
  1.  
  2. //don't forget the connexion to DB
  3.  
  4. function new_nb_visit()
  5.  
  6. {
  7.  
  8.    $q = "select new nb_visit from blabla...";
  9.  
  10.    $r = mysql_query($q)or mail("your mail in ", $_SERVER["PHP_SELF"], mysql_error()."\n".$q);//mail if the server is set to do so, otherwise you can die().
  11.  
  12.    $d = mysql_fetch_row($r);
  13.  
  14.    echo $d[0];//echo just the new value or some special displaying of this new value that will replace inside the div
  15.  
  16. }
  17.  
  18. /*in fact, in rpc.php do a dynamic call of he function so that you can use this little association for any div to update with anything to display in : */
  19.  
  20. $fonction = $_GET["f"];
  21.  
  22. $fonction();
  23.  
  24. /*I call the  right function thanks to the name passed to the httpquery inside the javascript function, the one that will send what I want to be displayed*/


this code, once you get it, can be used and used again just, using the f parameter for the function name defined on rpc.php and object_id (element to update on the page.




to use this or trigger this on the the page :
you div is like his

<div id="my_div">blabla</div>

and just fill it on any event for any object of the document you want.

onCLick/onChange/onload="Javascript : update_div('new_nb_visit', 'my_div');"

or with the timer function;

you can try first wih a refresh button
____________________
My web site[/url] oh sh..!
  • krismeister
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Oct 21, 2006
  • Posts: 202
  • Status: Offline

Post November 3rd, 2006, 5:32 pm

WOW now that is an example! gisele hooked you up with some nifty PHP which you can choose what PHP function to use.

2 quick comments before I continue:
You don't have to pass the DIV id into the PHP

gisele wrote:
/*call the remote script with the right name of the function and the div id as GET parameters*/
ajax.open('get', 'http://your_domain/your_path/rpc.php?object_id=' + object_id + '&f=' + f);


and if the below works (I don't have a php server to test) it's bizzar code(to me:)). The GET[] should return a string, then the 2nd line calls it like a function. I'd recommend using a SWITCH statment with $f.

gisele wrote:
$fonction = $_GET["f"];
$fonction();


Heres another way to do it. You'll need the http://prototype.conio.net/ framework.
Code: [ Download ] [ Select ]
<html>
<head>
<title>AJAX Return Visitors</title>
<script src="prototype.js" language="JavaScript" type="text/javascript"></script>
<script type="text/javascript" language="JavaScript">
function updateVisitors() {
    var url = 'page2.php';
    var params = '';
    var ajax = new Ajax.Updater(
        {success: 'visitorNumber'},
        url,
        {method: 'get', parameters: params, onFailure: reportError});
}

function reportError(request) {
$('visitorNumber').innerHRML = "Error";
}
</script>
</head>
<body>
<h1>My site has <span id="visitorNumber">unknown</span> visitors</h1>
<p><a href="#" onclick="updateVisitors();">click here to update</a>
</body>
</html>
  1. <html>
  2. <head>
  3. <title>AJAX Return Visitors</title>
  4. <script src="prototype.js" language="JavaScript" type="text/javascript"></script>
  5. <script type="text/javascript" language="JavaScript">
  6. function updateVisitors() {
  7.     var url = 'page2.php';
  8.     var params = '';
  9.     var ajax = new Ajax.Updater(
  10.         {success: 'visitorNumber'},
  11.         url,
  12.         {method: 'get', parameters: params, onFailure: reportError});
  13. }
  14. function reportError(request) {
  15. $('visitorNumber').innerHRML = "Error";
  16. }
  17. </script>
  18. </head>
  19. <body>
  20. <h1>My site has <span id="visitorNumber">unknown</span> visitors</h1>
  21. <p><a href="#" onclick="updateVisitors();">click here to update</a>
  22. </body>
  23. </html>


couple of cool features going on in the above. See the line {success: 'visitorNumber'} it looks like magic, but you feed the ID of the element you want populated and voila!!!!

Another fun prototype function is $() feed it an element ID and it returns that element.

I put the line var params = ''; in there so you can easily add gisele parameters if you want.

and the PHP would be something like:

page2.php
Code: [ Download ] [ Select ]
//find visitor number from database
echo $visitorNumber;
  1. //find visitor number from database
  2. echo $visitorNumber;


Now I'll leave it up to someone else to show you how to make it highlight and fade when it's updated. :wink:
  • gisele
  • Expert
  • Expert
  • User avatar
  • Joined: Nov 11, 2004
  • Posts: 579
  • Loc: Nimes (France)
  • Status: Offline

Post November 4th, 2006, 3:50 am

HI,

I understand your perplexity :-)
Maybe it's something new for you.
But I allays use dynamic function calls, no need switch or if/elseif.
I already use these kinds of things for various projects.
a very known way is the use of double $ ($$), have you ever seen that?
In fact, sometimes I use call_user_function_array() for a complex parameters managment.
But I often use dynamic call to functions and also class instances
PHP Code: [ Download ] [ Select ]
 
$class = 'my_class' ;//for instance a get/post parameter
 
$my_object = new $class(possible param....);
 
 
  1.  
  2. $class = 'my_class' ;//for instance a get/post parameter
  3.  
  4. $my_object = new $class(possible param....);
  5.  
  6.  

Or dynamic call from an object :
PHP Code: [ Download ] [ Select ]
 
$function = 'a_fonction';//maybe a value from a superglobal too
 
$my_object->$function();
 
$this->$function();
 
 
  1.  
  2. $function = 'a_fonction';//maybe a value from a superglobal too
  3.  
  4. $my_object->$function();
  5.  
  6. $this->$function();
  7.  
  8.  

that'll call the member function a_function() exactly like
PHP Code: [ Download ] [ Select ]
 
$my_object->a_function() ;
 
or
 
$this->a_function() ;
 
 
  1.  
  2. $my_object->a_function() ;
  3.  
  4. or
  5.  
  6. $this->a_function() ;
  7.  
  8.  

You're right, no need to pass the div id to php function ... in that particualr case.
Sometimes, on some examples, the div id was dynamically given, for example matching with an item in the data mode of the DB, so that it will be used in the php function.For example the same Id of an item to update in the db.
But you're right in that case that could disturb the understanding.
In fact What I wanted to do, was a generic mecanism that could be portable, usable from various contexts and many times.

We just have to add a needed php function in our own and dedicated php library on the rpc.php and pass its name to the local javascript function to use it.

The applications change, but only the funcion in rpc.php change.

each php function send the right html updating the specified div.


Yours is clean and simple to use , In fact both are very close but in your example something stay obscur in the mecanism for a beginner, because of the code layer to import.

yours is very simple and appropriate tu use it in that case anyway.

just a little typo :
$('visitorNumber').innerHRML = "Error";

I think it's "innerHTML"

For the displaying style, I think the best way is a ccs class to apply to your span.
____________________
My web site[/url] oh sh..!
  • krismeister
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Oct 21, 2006
  • Posts: 202
  • Status: Offline

Post November 4th, 2006, 5:55 am

Just thought of something. Its' a huge security whole to let users browser pass functions. A hacker could use it to call dangerous commands:
dl,system,exec,passthru,shell_exec

but to your last post

gisele wrote:
$function = 'a_fonction';//maybe a value from a superglobal too
$my_object->$function(); //same as $my_object->a_function() ;


Truthfully I haven't used PHP too much, It looks like something that would be nice for the future.

One thing if you're using an if/switch, a future developer can looks at the code and realize what what function are expected to be called.
  • gisele
  • Expert
  • Expert
  • User avatar
  • Joined: Nov 11, 2004
  • Posts: 579
  • Loc: Nimes (France)
  • Status: Offline

Post November 4th, 2006, 7:39 am

well,

We have no problem to force the mecanism not to work with a plain function name.

all the defined functions will have a prefix and the dynamic call will be a concatenation invisible for the user.

PHP Code: [ Download ] [ Select ]
 
$fonction  =  "any_prefix".$_GET["f"];
 
$fonction();
 
 
  1.  
  2. $fonction  =  "any_prefix".$_GET["f"];
  3.  
  4. $fonction();
  5.  
  6.  


If we really want a serious security, the problem is the same for any solution : there are ways to hide the remote script url(or protect the access to it) and also hide in the local source the call the local function.



In fact I don't really undestand the interest of "switch/else if" to know what function his expected to be called while they are just defined above.
on the contratry, it seems explict when you know that the name of the expected function must be "prefix" + param passed.
____________________
My web site[/url] oh sh..!
  • krismeister
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Oct 21, 2006
  • Posts: 202
  • Status: Offline

Post November 4th, 2006, 8:11 am

I'm fine with the prefix.

But it still requires a future developer to need to examine your entire page (or multiple pages) in order to find the function.

Maybe a comment would be as approrpiate as a switch.

PHP Code: [ Download ] [ Select ]
 
 
 
// possible values for f are
 
// visitorCount
 
// someFunction2
 
// someFunction3
 
 
 
$fonction = 'safe'.$_GET["f"];
 
$fonction();
 
 
 
 
  1.  
  2.  
  3.  
  4. // possible values for f are
  5.  
  6. // visitorCount
  7.  
  8. // someFunction2
  9.  
  10. // someFunction3
  11.  
  12.  
  13.  
  14. $fonction = 'safe'.$_GET["f"];
  15.  
  16. $fonction();
  17.  
  18.  
  19.  
  20.  


the other option is

PHP Code: [ Download ] [ Select ]
 
 
 
$passedFunction = $_GET["f"]
 
 
 
switch ($passedFunction) {
 
case 'visitorCount':
 
   visitorCount();
 
   break;
 
case 'someFunction2':
 
   someFunction2();
 
   break;
 
case 'someFunction3':
 
   someFunction3();
 
   break;
 
default:
 
   echo '<h1>Possible breech attempted on passed f: '.  $passedFunction . '.</h1>';
 
   exit();//stops the entire php process.
 
}
 
 
  1.  
  2.  
  3.  
  4. $passedFunction = $_GET["f"]
  5.  
  6.  
  7.  
  8. switch ($passedFunction) {
  9.  
  10. case 'visitorCount':
  11.  
  12.    visitorCount();
  13.  
  14.    break;
  15.  
  16. case 'someFunction2':
  17.  
  18.    someFunction2();
  19.  
  20.    break;
  21.  
  22. case 'someFunction3':
  23.  
  24.    someFunction3();
  25.  
  26.    break;
  27.  
  28. default:
  29.  
  30.    echo '<h1>Possible breech attempted on passed f: '.  $passedFunction . '.</h1>';
  31.  
  32.    exit();//stops the entire php process.
  33.  
  34. }
  35.  
  36.  


looking at the above, a future PHP developer will realize the code is setup with 3 values for f in mind.
  • krismeister
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Oct 21, 2006
  • Posts: 202
  • Status: Offline

Post November 4th, 2006, 8:22 am

actually i've sort of changed my mind,

maybe the prefix is better,

you can add functions without having to edit any code just name them

anyprefixSomeFunction3()

the confusing part would come when you have lots of functions available to you spread out on several pages. Thats when the switch would be valuable, you can tell exactly what functions can use.

Kris
  • gisele
  • Expert
  • Expert
  • User avatar
  • Joined: Nov 11, 2004
  • Posts: 579
  • Loc: Nimes (France)
  • Status: Offline

Post November 4th, 2006, 9:12 am

yeah why not

we also can imagine something that both sum up the differents cases and protect the mecanism :

PHP Code: [ Download ] [ Select ]
 
$function = $_GET["f"];
 
$func_list = array("visitorCount", "someFunction2" , "someFunction3");
 
if(in_array($function, $func_list))
 
      $fonction();
 
 
  1.  
  2. $function = $_GET["f"];
  3.  
  4. $func_list = array("visitorCount", "someFunction2" , "someFunction3");
  5.  
  6. if(in_array($function, $func_list))
  7.  
  8.       $fonction();
  9.  
  10.  


Of course my first work was just a suggestion, And I admit there is an unlimmitted number of ways to optimize this base ! :-)
____________________
My web site[/url] oh sh..!
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post November 4th, 2006, 9:12 am

Post Information

  • Total Posts in this topic: 16 posts
  • Users browsing this forum: spork and 216 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© Unmelted Enterprises 1998-2009. Driven by phpBB © 2001-2009 phpBB Group.