Skip to content

Instantly share code, notes, and snippets.

@aponxi
Last active July 30, 2023 21:22
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 24 You must be signed in to fork a gist
  • Save aponxi/4744599 to your computer and use it in GitHub Desktop.
Save aponxi/4744599 to your computer and use it in GitHub Desktop.
Simple chat script php

Very simple jQuery AJAX PHP chat

jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.

In other words it makes everything really simple. For this example you will need this file.

chat.sql

First step is creating a database. Name it "mysimplechat" or something like that. Then create a table named "chat", it should have 2 fields, Id and Text.

CREATE TABLE IF NOT EXISTS `chat` (
  `Id` int(11) NOT NULL auto_increment,
  `Text` text NOT NULL,
  PRIMARY KEY  (`Id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

server.php

Make a new file and name it server.php. This is full code, I will explain it part by part below.

<?
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'your password';
 
$conn = mysql_connect($dbhost, $dbuser, $dbpass) 
or die ('Error connecting to mysql');
 
$dbname = 'chat_database';
 
mysql_select_db($dbname);
 
$message = $_POST['message'];
 
if($message != "")
{
 $sql = "INSERT INTO `chat` VALUES('','$message')";
 mysql_query($sql);
}
 
$sql = "SELECT `Text` FROM `chat` ORDER BY `Id` DESC";
$result = mysql_query($sql);
 
while($row = mysql_fetch_array($result))
 echo $row['Text']."\n";
 
 
?>

Ok this script is very simple.

First it connects to database. Don't forget to set your own database information (host,username,password and database name).

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'your password';
 
$conn = mysql_connect($dbhost, $dbuser, $dbpass) 
or die ('Error connecting to mysql');
 
$dbname = 'chat_database';
 
mysql_select_db($dbname);
?>

Then receives $message variable with POST method.

$message = $_POST['message'];

If received message wasn't blank, add it to database.

if($message != "")
{
 $sql = "INSERT INTO `chat` VALUES('','$message')";
 mysql_query($sql);
}

Then show all rows from table "chat".

$sql = "SELECT `Text` FROM `chat` ORDER BY `Id` DESC";
$result = mysql_query($sql);
 
while($row = mysql_fetch_array($result))
 echo $row['Text']."\n";

index.php

And that's it! So let's jump to jQuery part. Make a new file and name it anything you want. I used index.php, but It can also be regular HTML file.

<html>
<head>
<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<script type="text/javascript">  
 
function update()
{
    $.post("server.php", {}, function(data){ $("#screen").val(data);});  
 
    setTimeout('update()', 1000);
}
 
$(document).ready(
 
function() 
    {
     update();
 
     $("#button").click(    
      function() 
      {         
       $.post("server.php", 
    { message: $("#message").val()},
    function(data){ 
    $("#screen").val(data); 
    $("#message").val("");
    }
    );
      }
     );
    });
 
 
</script>
</head>
<body>
 
<textarea id="screen" cols="40" rows="40"> <//textarea> <br>  
<input id="message" size="40">
<button id="button"> Send </button>
 
</body>
</html>

This can seem a little confusing at start but it is pretty simple.

First it includes jQuery script

<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>

Then we define a new function. It's used to open server.php (the PHP script I described just above) and copy all content from it to a textbox with id = screen. And as you can see above content of server.php will be list of all messages.

 
  function update()
    {
     $.post("server.php", {}, function(data){ $("#screen").val(data);});  
 
     setTimeout('update()', 1000);
    }

In this part we use $.post method, which is described well here. But I will try to explain it myself anyway.

  • Make a POST request $.post
  • Target server.php script "server.php",
  • Here is the list of all variables we want to send, (in this case none) {},

If everything goes well execute this function Content from targeted script (server.php) is stored inside variable "data". Set the value of textarea with id = screen to data.

function(data) 
{ 
$("#screen").val(data) 
;}

We want our script to check server for new messages every second. We will make an recursive function, each time it runs it will call itself but after 1 second, so it will execute itself every second.

setTimeout('update()', 1000);

So we are done with update() function.

Now we check if page is fully loaded before doing anything.

$(document).ready(function()

Then we call update() function once and it will keep calling itself.

update();

Now when element with id = button is clicked, we must send new message to server and update our "screen" (a textbox with id = screen).

This part is very similar to update() function except, in this case we send one variable with POST method, and it is content of new message which is inside the input box with id = message.

$("#button").click(    
 function() 
 {         
  $.post("server.php", 
  {message: $("#message").val()},
  function(data){ 
   $("#screen").val(data); 
   $("#message").val("");
   }
  );
 }
);

And that's it! Now just add textarea, input box and a button with right id-s!

 
 <textarea id="screen" cols="40" rows="40"> <//textarea> <br>  
 <input id="message" size="40">
 <button id="button"> Send </button>
@alisajidcs
Copy link

That's a lame method for chat app

@NasibullohM
Copy link

it doesnt work, what about including files

@mrtnctproo
Copy link

Thank you for such light, easy and simple instant chat ! I'll be having a field day customizing it and of course, you will be credited :) 👍

@Konameme
Copy link

I can't get SQL to work on my server. Any help?

@SosEquus
Copy link

as you may know, never trust the use input, as i don t trust any "free source" , couse all doesn t work, without a small "trick" , which creator keep it for himself, he thinks that inented the wheel... poor , really poor example(not complete, and not safe at all), and you can find it on github... thts hilarious

@drobesko
Copy link

ugly.

then you make another, pretty one

@PyMaster22
Copy link

The database didn't work. I am using SQLite because it is free. The error I received was:
near "auto_increment": syntax error: CREATE TABLE IF NOT EXISTS `chat` (
`Id` int(11) NOT NULL auto_increment
I don't know what it means. I just cam across this while trying to find PHP web chat code.

@Maks1116
Copy link

Activate your windows bro.

That's exactly with what this person needed help.

@wethecom
Copy link

wethecom commented Dec 25, 2020

The database didn't work. I am using SQLite because it is free. The error I received was:
near "auto_increment": syntax error: CREATE TABLE IF NOT EXISTS `chat` (
`Id` int(11) NOT NULL auto_increment
I don't know what it means. I just cam across this while trying to find PHP web chat code.

setting column as PRIMARY KEY is an AUTOINCREMENT. So there is no need of specifying explicitly column as AUTOINCREMENT.
try removing it or mabey this will work changing caps

CREATE TABLE IF NOT EXISTS chat (
Id int(11) NOT NULL PRIMARY KEY AUTOINCREMENT,
Text text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
or try AUTO_INCREMENT

@Umar-Soft
Copy link

Activate your windows bro.
we are not here for windows activation we are here for the error solution
That's exactly with what this person needed help.

@Joseph-Ayub
Copy link

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment