· 6 years ago · May 06, 2019, 05:10 AM
1# Very simple jQuery AJAX PHP chat
2
3jQuery 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.
4
5In other words it makes everything really simple.
6For this example you will need this file.
7
8## chat.sql
9
10First step is creating a database.
11Name it "mysimplechat" or something like that.
12Then create a table named "chat", it should have 2 fields, Id and Text.
13
14```sql
15CREATE TABLE IF NOT EXISTS `chat` (
16 `Id` int(11) NOT NULL auto_increment,
17 `Text` text NOT NULL,
18 PRIMARY KEY (`Id`)
19) ENGINE=MyISAM DEFAULT CHARSET=latin1;
20```
21
22## server.php
23
24Make a new file and name it `server.php`.
25This is full code, I will explain it part by part below.
26
27```php
28<?
29$dbhost = 'localhost';
30$dbuser = 'root';
31$dbpass = 'your password';
32
33$conn = mysql_connect($dbhost, $dbuser, $dbpass)
34or die ('Error connecting to mysql');
35
36$dbname = 'chat_database';
37
38mysql_select_db($dbname);
39
40$message = $_POST['message'];
41
42if($message != "")
43{
44 $sql = "INSERT INTO `chat` VALUES('','$message')";
45 mysql_query($sql);
46}
47
48$sql = "SELECT `Text` FROM `chat` ORDER BY `Id` DESC";
49$result = mysql_query($sql);
50
51while($row = mysql_fetch_array($result))
52 echo $row['Text']."\n";
53
54
55?>
56```
57
58Ok this script is very simple.
59
60First it connects to database.
61Don't forget to set your own database information (host,username,password and database name).
62
63```php
64<?php
65$dbhost = 'localhost';
66$dbuser = 'root';
67$dbpass = 'your password';
68
69$conn = mysql_connect($dbhost, $dbuser, $dbpass)
70or die ('Error connecting to mysql');
71
72$dbname = 'chat_database';
73
74mysql_select_db($dbname);
75?>
76```
77
78
79
80Then receives $message variable with POST method.
81
82```php
83$message = $_POST['message'];
84```
85
86
87
88If received message wasn't blank, add it to database.
89
90```php
91if($message != "")
92{
93 $sql = "INSERT INTO `chat` VALUES('','$message')";
94 mysql_query($sql);
95}
96```
97
98
99
100Then show all rows from table "chat".
101
102```php
103$sql = "SELECT `Text` FROM `chat` ORDER BY `Id` DESC";
104$result = mysql_query($sql);
105
106while($row = mysql_fetch_array($result))
107 echo $row['Text']."\n";
108```
109
110
111
112## index.php
113
114And that's it!
115So let's jump to jQuery part.
116Make a new file and name it anything you want.
117I used index.php, but It can also be regular HTML file.
118
119```html
120<html>
121<head>
122<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
123<script type="text/javascript">
124
125function update()
126{
127 $.post("server.php", {}, function(data){ $("#screen").val(data);});
128
129 setTimeout('update()', 1000);
130}
131
132$(document).ready(
133
134function()
135 {
136 update();
137
138 $("#button").click(
139 function()
140 {
141 $.post("server.php",
142 { message: $("#message").val()},
143 function(data){
144 $("#screen").val(data);
145 $("#message").val("");
146 }
147 );
148 }
149 );
150 });
151
152
153</script>
154</head>
155<body>
156
157<textarea id="screen" cols="40" rows="40"> <//textarea> <br>
158<input id="message" size="40">
159<button id="button"> Send </button>
160
161</body>
162</html>
163```
164
165
166
167This can seem a little confusing at start but it is pretty simple.
168
169First it includes jQuery script
170
171```html
172<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
173```
174
175Then we define a new function.
176It'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.
177
178```php
179
180 function update()
181 {
182 $.post("server.php", {}, function(data){ $("#screen").val(data);});
183
184 setTimeout('update()', 1000);
185 }
186```
187
188In this part we use $.post method, which is described well here. But I will try to explain it myself anyway.
189
190- Make a POST request `$.post`
191- Target server.php script `"server.php", `
192- Here is the list of all variables we want to send, (in this case none) `{},`
193
194If everything goes well execute this function
195Content from targeted script (server.php) is stored inside variable "data".
196Set the value of textarea with id = screen to data.
197
198```js
199function(data)
200{
201$("#screen").val(data)
202;}
203```
204
205
206
207We want our script to check server for new messages every second.
208We will make an recursive function, each time it runs it will call itself but after 1 second, so it will execute itself every second.
209
210
211`setTimeout('update()', 1000); `
212
213
214
215
216So we are done with `update()` function.
217
218Now we check if page is fully loaded before doing anything.
219
220
221`$(document).ready(function() `
222
223
224
225
226Then we call update() function once and it will keep calling itself.
227
228
229`update();`
230
231
232
233
234Now when element with id = button is clicked, we must send new message to server and update our "screen" (a textbox with id = screen).
235
236This 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.
237
238```js
239$("#button").click(
240 function()
241 {
242 $.post("server.php",
243 {message: $("#message").val()},
244 function(data){
245 $("#screen").val(data);
246 $("#message").val("");
247 }
248 );
249 }
250);
251```
252
253
254
255And that's it! Now just add textarea, input box and a button with right id-s!
256```html
257
258 <textarea id="screen" cols="40" rows="40"> <//textarea> <br>
259 <input id="message" size="40">
260 <button id="button"> Send </button>
261```