Jump to content

reloading a page without refresh


skatermike21988

Recommended Posts

ok, i am needing to know of a way to reload a page without having to refresh, what i have is a instant messenger that sends a request to a user, if the user is browseing my site and they recieve a request while looking at a page it will show up on the page that they have a incoming request, right now the way i have it is that the page has to be refreshed or the user has to go to another page before it displays that they have a request.

All help appreciated.

BTW, I have looked into javascript but have NEVER used or fooled around with javascript so i have absolutely no idea on what i am doing.
Link to comment
Share on other sites

Well not sure 100% the best way of doing this. Perhaps have a javascript timer that will activate a link for a transparent frame with a url for the user id in handling script or use a $_SESSION user id for a more secure system, this will direct to a script that will collect the get and query the database to see if a message has been set in the database if it has it will pull the information and update the messenger again using javascript.

I think either way this will be about 80% javascript and 20% php.

Link to comment
Share on other sites

I am going to have something similar in a live support app that I am developing.

Here is what I am going to do. This is more like what SMF does to inform the users of a new message.

The javascript

[code=php:0]
//I am not going to pretend that I completely understand this but it works
//this creates the request object
//for more informaton google XMLHttpRequest
function createRequestObject()
{
   if (window.XMLHttpRequest) { // Mozilla, Safari, Opera...
       var xmlhttp = new XMLHttpRequest();
       if (xmlhttp.overrideMimeType)
          xmlhttp.overrideMimeType('text/xml');
       }
       else if (window.ActiveXObject)
{ // IE
       try {
           var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
           try {
               var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
       }
   }

   if (!xmlhttp) {
       alert('Giving up :( Cannot create an XMLHTTP instance');
       return false;
   }
return xmlhttp;
}

//here we define global variables for the following functions
var http = createRequestObject();
var mTimer;

//this function will be called when the page loads.
function pageLoad() {
    checkMessages();
}

//how we redirect the user if they have messages
function redirector() {
     window.location = 'http://www.yoursite.com/yourInbox.php';
}

function checkMessages() {
    //we open the file for processing with the get method
    http.open('get', 'yourpage.php?action=checkMessages');
    http.setRequestHeader('Content-Type', 'application/x-www-urlencoded');
    //if the page was opened successfuly we move on to the next function
    http.onreadystatechange = handleRequest();
    //this is the only real difference between the get and post method.
    //if we were posting something we would do something like this
    //http.send('var='+yourvar);
    http.send(null);
}

function handleRequest() {
    if (http.readystate == 4) {
        //the response from the php backend file
        var response = http.responseText;
        if (response == '') {
            //if the response is empty we set a timer to recheck for messages every 5 seconds
            mTimer = setTimeout('checkMessages();', 5000);
          } else {
            //we clear the timer
            clearInterval(mTimer);
            //confirm is alot like alert except that you can choose two options
            var agree = confirm(response);
            if (agree) {
                //if the user has messages and agrees to be redirected to the inbox
               setTimeout('redirector()', 5000);
                //this is realy unnecssicary. I only put this here so you would see the difference between alert and confirm
               alert('You will be redirected to your inbox/whatever in 5 seconds');
            }
      }
}[/code]

Now in the body of your html place this

[code]
<body onload="javascript:pageLoad();">

[/code]

Now you can do something like this in the php script. NOTE you will have to change the location of the file in the getMessages function and the redirect in the handleRequest function.

[code]
<?php
session_start();
//this is going to assume that the user is logged in.

$vaild_actions = array('checkMessages', 'something else');
$action = strip_tags($_GET['action']);
if (!in_array($action, $valid_actions)) {
   die("invaild action");
}

if ($action == "checkMessages") {
  if (!$_SESSION['username']) {
      echo "";
      exit();
  }
  $sql = sprintf("SELECT COUNT(*) AS `message_check` FROM `table` WHERE `username` = '%s'", $_SESSION['username']);
  $res = mysql_query($sql);
  $message_check = mysql_result($res, 0, 'message_check');
 
  if ($message_check == 0) {
      echo "";
  }else{
     echo "You have $message_check new messages. Click ok to view your inbox/whatever";
  }
}
?>
[/code]
     
hope this helps,
Tom       


Link to comment
Share on other sites

I just thought of something..

You may run into an issue. This being that if the user chooses not to be redirected it will still check for new messages and will pop up every 5 seconds..lol

You may want to add something to the message table.. like popup or whatever.

Now when you add the message to the db set that field to accept. and if they deny the pop up do something like this..

first change this

[code=php:0]
$sql  = sprintf("SELECT COUNT(*) AS `message_check` FROM `table` WHERE `username` = '%s'", $_SESSION['username']);
[/code]

To

[code=php:0]
$popup = "accept";
$sql = sprintf("SELECT COUNT(*) AS `message_check` FROM `table` WHERE `username` = '%s' AND `popup` = '%s'", $_SESSION['username'], $popup);

And now add this function to the javascript..

[code=php:0]
var deny = createRequestObject();
function denyPopup() {
    deny.open('get', 'yourpage.php?action=denyPopup');
    deny.setRequestHeader('Content-Type', 'application/x-www-urlencoded');
    deny.onreadystatechange = handleDeny();
    deny.send(null);
}

function handleDeny() {
    if (deny.readystate == 4) {
      var response = deny.responseText;
      alert(response);
    }
}
[/code]

and now you can add this to the php backend file

[code=php:0]
if ($action == "denyPopup") {
  $username = $_SESSION['username'];
  $sql = "UPDATE `table` SET `popup` = 'deny' WHERE `username` = '$username'";
  $res = mysql_query($sql);
  if (!$res) {
      echo "There was an error";
  }else{
      echo "Your messages are in your inbox when you are ready";
  }
}[/code]

You will also need to add the denyPopup to the vaild actions array.

also, chage the handleRequest function to this.

[code=php:0]
function handleRequest() {
    if (http.readystate == 4) {
        //the response from the php backend file
        var response = http.responseText;
        if (response == '') {
            //if the response is empty we set a timer to recheck for messages every 5 seconds
            mTimer = setTimeout('checkMessages();', 5000);
          } else {
            //we clear the timer
            clearInterval(mTimer);
            //confirm is alot like alert except that you can choose two options
            var agree = confirm(response);
            if (agree) {
                //if the user has messages and agrees to be redirected to the inbox
                setTimeout('redirector()', 5000);
                //this is realy unnecssicary. I only put this here so you would see the difference between alert and confirm
                alert('You will be redirected to your inbox/whatever in 5 seconds');
            } else {
                denyPopup();
            }
      }
}[/code]

That should fix the bug..

Good luck and Enjoy,
Tom

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.