简体   繁体   中英

How do I auto-refresh my php chat-script?

I am having trouble getting my php chat script to auto refresh when mysql data is changed. I have done a good bit of research and it seems a lot of other people's solutions are more complicated then what I need (I'm going for something very basic).

I do not know any javascript so detailed comments would be appreciated if js is involved.

Here is the php script that I have created. It is functioning (at least for me).

    include 'connect2.php';
    echo "
            Enter a Message:
            <form method=post action='' name=chat>
            <input type=text name=message>
            <input type=submit name=chat value=Submit>
            </form>
    ";

    if (isset($_POST['chat'])) {
    $message = $_POST['message'];
    mysql_query("INSERT INTO chat set message='$message',user='$_SESSION[username]'");
    }

    $sql = "select * from chat order by id desc limit 15";
    $result = mysql_query($sql) or die ("An error has occured with in the database.");

    while ($data = mysql_fetch_assoc($result)) {
    $db_message = $data['message'];
    $db_user = $data['user'];
    echo "$db_user : $db_message <br>";
    }

    ?>

Any help would be appreciated, thanks! :)

You can use setInterval and jQuery library ajax functions to check for it.

For example, it's very simple to do with jQuery :

$(document).ready(function() {
  // check once in five seconds
  setInterval(function() {
    $.get('/script.php', {do: 'new_messages'}, function(response) {
      if(response == 1) {
        window.location.reload();
      }
    });
  }, 5000); 
});

And somewhere on server:

if(isset($_GET['do']) && $_GET['do'] == 'new_messages') {
  // some your code that detects if there's any new messages, and sets
  // $there_are_new_messages to true, if there's any
  ...
  if($there_are_new_messages) {
     echo 1; 

     exit; // avoid further output
  }
}

Please remember, that for this to work you need to ensure that there's no output before ajax block, as you can get into unexpected results.

Also consider that using output is not a good practice at all to show your script everything is ok. Better way is to set HTTP header with corresponding response code.

The best way to do this in your case would probably be using Ajax (and jQuery) and refreshing every X seconds.

Ready Handler- http://api.jquery.com/ready/

Javascript Timer- http://www.w3schools.com/js/js_timing.asp

Ajax Request- http://api.jquery.com/jQuery.post/

PHP json_encode- http://php.net/manual/en/function.json-encode.php

$( document ).ready(function() { //set up refresh timer on page load
    var refreshTimer = setInterval(function(){refreshMessages()},5000); //creates timer to request every 5 seconds
});

function refreshMessages(){
    $.post( "getMessages.php", function( data ) { //fire ajax post request
        alert("Got messages: " + data); // this just alerts the data when the request is done, you'll probably want to format/print
    });
}

On the getMessages.php side of things, you'll want to pull your messages from the database how you normally would. In this case, json encoding your php messages array would be an easy way for you to iterate the returned object.

<?php
$messages = // get messages array from database
echo json_encode($messages);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM