Skip to content

Instantly share code, notes, and snippets.

@aponxi

aponxi/README.md

Last active May 23, 2021
Embed
What would you like to do?
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>
@k1ng440

This comment has been minimized.

Copy link

@k1ng440 k1ng440 commented Feb 9, 2013

ugly.

@CodyKochmann

This comment has been minimized.

Copy link

@CodyKochmann CodyKochmann commented Oct 27, 2015

Ugly in the terms of if you had other things built into it. If it was standalone and had nothing more to it then it is a well put together big picture. I'm still new at php and sql and this really helped in the overall understanding of it.

@putrantos

This comment has been minimized.

Copy link

@putrantos putrantos commented Oct 31, 2015

asdasd

@putrantos

This comment has been minimized.

Copy link

@putrantos putrantos commented Oct 31, 2015

mnbmnbmnbmn

@putrantos

This comment has been minimized.

Copy link

@putrantos putrantos commented Oct 31, 2015

asdxadsasd

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jun 2, 2016

CodyKochmann commented on Oct 27, 2015
Ugly in the terms of if you had other things built into it. If it was standalone and had nothing more to it then it is a well put together big picture. I'm still new at php and sql and this really helped in the overall understanding of it.

GotNoHatersGotNoSwag . fuck em

@laurentP13

This comment has been minimized.

Copy link

@laurentP13 laurentP13 commented Jun 11, 2016

Simple, minimal, very clear. Thank you. Explains all the fundamentals.

@shashibest

This comment has been minimized.

Copy link

@shashibest shashibest commented Jul 18, 2016


Notice: Undefined index: message in D:\xampp\htdocs\ASPL1\Chat\server.php on line 13
this is error but code run
@rimsha95

This comment has been minimized.

Copy link

@rimsha95 rimsha95 commented Mar 14, 2017

Abe saaare mil k hume chutiya bana rahe hai! kya hai download may dekha hai khud ne?Bhosdike dekh to h le de kya raha hai tu! and jab samjh jaaye so mail kar diyo.

@GafferAsad

This comment has been minimized.

Copy link

@GafferAsad GafferAsad commented Jun 14, 2017

bro please help me on one thing

@GafferAsad

This comment has been minimized.

Copy link

@GafferAsad GafferAsad commented Jun 14, 2017

image

@Ki-Tech

This comment has been minimized.

Copy link

@Ki-Tech Ki-Tech commented Aug 8, 2017

you can fix that with css

@ErikThiart

This comment has been minimized.

Copy link

@ErikThiart ErikThiart commented Sep 6, 2017

Activate your windows bro.

@seddik

This comment has been minimized.

Copy link

@seddik seddik commented Oct 21, 2017

God bless you, if you could add readonly attribute to the textarea

@alisajidcs

This comment has been minimized.

Copy link

@alisajidcs alisajidcs commented Apr 29, 2018

That's a lame method for chat app

@NasibullohM

This comment has been minimized.

Copy link

@NasibullohM NasibullohM commented May 4, 2018

it doesnt work, what about including files

@mrtnctproo

This comment has been minimized.

Copy link

@mrtnctproo mrtnctproo commented Jul 22, 2018

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

This comment has been minimized.

Copy link

@Konameme Konameme commented Nov 27, 2018

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

@SosEquus

This comment has been minimized.

Copy link

@SosEquus SosEquus commented Jul 28, 2019

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

This comment has been minimized.

Copy link

@drobesko drobesko commented Dec 11, 2019

ugly.

then you make another, pretty one

@PyMaster22

This comment has been minimized.

Copy link

@PyMaster22 PyMaster22 commented Jul 8, 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.

@Maks1116

This comment has been minimized.

Copy link

@Maks1116 Maks1116 commented Dec 16, 2020

Activate your windows bro.

That's exactly with what this person needed help.

@wethecom

This comment has been minimized.

Copy link

@wethecom 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

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