Welcome Guest ( Log In | Register )



2 Pages V   1 2 >  
Reply to this topicStart new topic
> Ajax + Php + Sql = Simply Superb! ( With Visitor Tracking ), A small tutorial to explain integrating php, ajax and MySQL Database
Rating 5 V
Niru
post Apr 14 2007, 01:52 PM
Post #1


Advanced Member
Group Icon

Group: Members
Posts: 190
Joined: 18-August 06
From: Fun.NiranVv.Com
Member No.: 15,325



Hi all..

I'm back with a new small tutorial!

Introducation

A tutorial to integrate Ajax, Php And Database ( Im using MySQL) + Visitor Tracking!

Here you can enter values to some input fields, and by clicking some enter button, ( or u can call the function on some other event) those values will be sent to the database, along with visitor details ( IP Address, Input Value, Visitor Agent etc)! Those values will be stored in some database and you can retrieve the same using some simple php code and even deleted some
rows from those databases!

Requirements:If you don't have these requirements, then don't worry!! Have a look at those cool articles! ( Click on those above links)
You can learn the basics in some minutes biggrin.gif ( Yes.. Its true)

So Shall we start??

Stage 1: Create Database Table

Ok, First we have to analyze the requirements, we have to store the Input value, Ip address, visitor agent and timestamp in database! Remember, we need to create some Index field for the database

So, Im creating 5 fields, slno, test, ipaddr, agent, timer!
here is the SQL statement to run!
Im going to name the table as ajax


CODE
CREATE TABLE `ajax` (
`slno` INT( 4 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`test` VARCHAR( 50 ) NULL ,
`ipaddr` VARCHAR( 20 ) NULL ,
`agent` VARCHAR( 200 ) NULL ,
`timer` VARCHAR( 10 ) NULL
);



Stage 2: Design Main Interface Page
Now we are going to design one User interface, where we need to show one textbox and one button!
Clicking that button, should send the values to the database in the background!

HTML
<form>
<input id="test" value="" name="test" size="30" > <input class="button" value="Enter" type="button">
</form>


The main interface is over! Now we have to create the Ajax script to send the values to some script file using that we have to store the values in the database!

Usually, Ajax script will have the same format only, we need to change some little attributes only!

The following is the General format for Ajax!
HTML
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
</script>

Thanks to w3schools: http://www.w3schools.com/ajax/ajax_browsers.asp

Im going to modify this script and the modified one will be like this!



var word = document.getElementById('test').value;
var queryString = "?word=" + word;
ajaxRequest.open("GET", "php_ajax_input_script.php" + queryString, true);
ajaxRequest.send(null);
//alert(queryString);



Please have a look at those in red color!!
Im getting the value from that textbox named "test" and storing that in variable "word"
Then we have to pass the value in query string!
So we are attaching that to query string by assigning the value to "word"
And we are calling one new script file, where it will get values from the query string and store it to database!
If you need to check whether the script is called or not, we can display the value in some alert box!
We are going to call this on button click like this:

<input class="button" onClick="ajaxFunction();" value="Enter" type="button">

So, the final main page will look like this!

HTML
<html>
<head>

<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){

var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}

var word = document.getElementById('test').value;
var queryString = "?word=" + word;
ajaxRequest.open("GET", "php_ajax_input_script.php" + queryString, true);
ajaxRequest.send(null);
alert(queryString);
}

//-->
</script>
<title>php + Ajax + SQL Tutorial</title></head>
<body>
<form>
<input id="test" value="" name="test" size="30" style="color:#990000; font-weight:bold"> <input class="button" onClick="ajaxFunction();" value="Enter" type="button">
</form>
<a href="php_ajax_output.php">Check Live Table</a>
</body>

</html>



Stage 3: Create Script File to pass the values to database

We can get visitor IP address by this and storing that to variable:$ClientIP


if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ClientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ClientIP = $_SERVER['REMOTE_ADDR'];
}


We can get hostname also using php script! But here we are not going to get at this time, because it will slow down the process, and also will waste one database field! We can get it later while displaying the values!

Next we have to get visitor agent! For that we can use like this:

$ClientAgent = $_SERVER['HTTP_USER_AGENT'];

We can get current time stamp using this:

$MyTimeStamp = time();

And get the field value from the url ( Query String)

$word = $_GET['word'];

Now we can insert those values to the database by using this query:

$query = "INSERT INTO ajax(ipaddr, agent, test, timer) VALUES('$ClientIP', '$ClientAgent', '$word','$MyTimeStamp')";

So final page will look like this:

HTML
<?php
$dbhost = "localhost";
$dbuser = "dbUserName";
$dbpass = "dbPassword";
$dbname = "DatabaseName";

//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);

//Select Database
mysql_select_db($dbname) or die(mysql_error());

if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ClientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ClientIP = $_SERVER['REMOTE_ADDR'];
}
//$ClientHost = gethostbyaddr($ClientIP);
$ClientAgent = $_SERVER['HTTP_USER_AGENT'];
$MyTimeStamp = time();


// Retrieve data from Query String
$word = $_GET['word'];

// Escape User Input to help prevent SQL Injection
$word = mysql_real_escape_string($word);


//build query
$query = "INSERT INTO ajax(ipaddr, agent, test, timer) VALUES('$ClientIP', '$ClientAgent', '$word','$MyTimeStamp')";

//Execute query

// Exit if calling directly the script file!
if ($word != "")
{
$qry_result = mysql_query($query) or die(mysql_error());
}
else
{
echo '<b>Hacking Attempt!!</b><br><br>';
}


?>


Now, If you enter some values in the input field and click that enter button, the value will be send to the background script file using query string and the script will get values from that query string and store that values in the database along with ipaddr, visitor agent and timestamp!

You can try this script here:

Fun.niranvv.com/test/php_ajax_input.php

Enter some values there in that page and it will call script here:

Fun.niranvv.com/test/php_ajax_input_script.php

You can check the database values here:

Fun.niranvv.com/test/php_ajax_output.php

You can even delete values from those databases!!
Feel free to play with those pages! You can delete those values from database!
Im using one separate demo database for this tutorial!
So no issues with playing with those pages and live databaases!

:: Part 1 Over ::


Part 2: Updating one status message on the main page after running the script successfully
( Part 2: Over :: Check it here)
Part 3: Displaying the values from the database using php and deleting those values by checking the checkboxes as displayed here:
Fun.niranvv.com/test/php_ajax_output.php
Part 4: Integrating Part 2 and Part 3 to display the updated table in the same page itself!!
( Part 3 and Part 4 are integrated here



Love,
Niru

This post has been edited by Niru: Apr 15 2007, 09:55 AM
Go to the top of the page
 
+Quote Post
livingston
post Apr 14 2007, 05:35 PM
Post #2


Advanced Member
Group Icon

Group: Members
Posts: 149
Joined: 14-February 07
From: Tuticorin, India
Member No.: 20,415



hi Niru this is really very great.

I really wanted to learn AJAX and now your tutorial has helped me to understand it better. Hope to learn more from you. smile.gif
Go to the top of the page
 
+Quote Post
TavoxPeru
post Apr 15 2007, 12:02 AM
Post #3


Super Member
Group Icon

Group: [HOSTED]
Posts: 760
Joined: 8-April 06
From: Lima - Peru
Member No.: 12,579



Hi Niru, excellent tutorial, simple, direct and easy to follow, for a while i'm learning this to apply in a new project that i'm just developing, congratulations and i hope that you can publish shortly the nexts parts.

Best regards,

Go to the top of the page
 
+Quote Post
Niru
post Apr 15 2007, 03:00 AM
Post #4


Advanced Member
Group Icon

Group: Members
Posts: 190
Joined: 18-August 06
From: Fun.NiranVv.Com
Member No.: 15,325



So , now we can move to the next section!!

Part 2: Displaying updated status message on the main page!

So, what we are going to do is, we have to display one status message on the main page after calling the background script file and after the successful insertion of values to the database!

Phase 1:

I'm going to show the values inserting to database one one new div!

So, Insert one DIV in main page and give some unique ID to that div! Im giving 'ajaxDiv' as the ID for the DIV!!

<div id='ajaxDiv'>Its Div Named "ajaxDiv". Your result will display here.....</div>


Phase 2:

Now we have to edit the background script file to echo some status message in the response over successful insertion of the values to database!

I'm editing the execute query function and inserting one more line to display the values like this:

if ($word != "")
{
$qry_result = mysql_query($query) or die(mysql_error());
echo "Updated Successfully with values IP :$ClientIP<br>Visitor Agent: $ClientAgent<br>Input Word: $word<br>Current Time Stamp: $MyTimeStamp";
}
else
{
echo '<b>Hacking Attempt!!</b>';
}

Thats over in the background script path!!
This will return the values while calling the script in the background!

Phase 3:

Now we have to write the values to the new div named "ajaxDiv" which is already created in the phase 1 in this Part 2
We can assign values to the div by using "
DivID.innerHTML = some value

We can get the string value from the response by using this function:
Request.responseText

So, we are going insert one function in the javascript path like this:

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;

}
}


Now the modifications are over!

So the final page will be like this:

Main interface (php_ajax_input.php)
HTML
<html>
<head>

<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){

var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var word = document.getElementById('test').value;
var queryString = "?word=" + word;
ajaxRequest.open("GET", "php_ajax_input_script.php" + queryString, true);
ajaxRequest.send(null);
//alert(queryString);
}

//-->
</script>
<title>php + Ajax + SQL Tutorial</title></head>
<body>
<form>
<input id="test" value="" name="test" size="30" style="color:#990000; font-weight:bold">&nbsp;&nbsp;<input class="button" onClick="ajaxFunction();" value="Enter" type="button">
</form>
<div id='ajaxDiv'>Its Div Named "ajaxDiv". Your result will display here.....</div>
<a href="php_ajax_output.php">Check Live Table</a>
</body>

</html>


Background script file (php_ajax_input_script.php)
HTML
<?php
$dbhost = "localhost";
$dbuser = "uSERnAME";
$dbpass = "pASSWORD";
$dbname = "dATABASENAME";

//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);

//Select Database
mysql_select_db($dbname) or die(mysql_error());

if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ClientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ClientIP = $_SERVER['REMOTE_ADDR'];
}
//$ClientHost = gethostbyaddr($ClientIP);
$ClientAgent = $_SERVER['HTTP_USER_AGENT'];
$MyTimeStamp = time();


// Retrieve data from Query String
$word = $_GET['word'];

// Escape User Input to help prevent SQL Injection
$word = mysql_real_escape_string($word);


//build query
$query = "INSERT INTO ajax(ipaddr, agent, test, timer) VALUES('$ClientIP', '$ClientAgent', '$word','$MyTimeStamp')";

//Execute query

// Exit if calling directly the script file!
if ($word != "")
{
$qry_result = mysql_query($query) or die(mysql_error());
echo "Updated Successfully with values IP :$ClientIP<br>Visitor Agent: $ClientAgent<br>Input Word: $word<br>Current Time Stamp: $MyTimeStamp";
}
else
{
echo '<b>Hacking Attempt!!</b><br><br>';
}
?>


Check the updated page here:
Fun.niranvv.com/test/php_ajax_input.php

..:: Part 2 Over ::..

Part 3 ( Coming Next ): Displaying the values from the database using php and deleting those values by checking the checkboxes as displayed here: Fun.niranvv.com/test/php_ajax_output.php

Update: Part 3 and Part 4 are integrated here:
Ajax+php+sql=simply Superb!(with Visitor Tracking) :: Section 2 (retrive Values From Database And Dynamic Update!)

This post has been edited by Niru: Apr 20 2007, 07:17 AM
Go to the top of the page
 
+Quote Post
iGuest
post Dec 1 2007, 01:11 PM
Post #5


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



"visitar tracking" concept was very useful for learning ajax and how to use ajax.thanking you....

-arasapandy
Go to the top of the page
 
+Quote Post
Andres Martinez ...
post Dec 21 2007, 07:03 AM
Post #6


Newbie [ Level 2 ]
Group Icon

Group: Members
Posts: 19
Joined: 14-December 07
From: Mexico
Member No.: 26,890



Nice tutorial!

I have a question, is it possible to store the retrieved results by Ajax in JavaScript variables instead of writing the results in a div html label??

I want to do this because I want to retrieve some data that would be used by some JavaScript functions that are already included in the page.
Go to the top of the page
 
+Quote Post
TavoxPeru
post Dec 22 2007, 11:09 AM
Post #7


Super Member
Group Icon

Group: [HOSTED]
Posts: 760
Joined: 8-April 06
From: Lima - Peru
Member No.: 12,579



QUOTE(Niru @ Apr 14 2007, 10:00 PM) *
So , now we can move to the next section!!
...
Check the updated page here:
Fun.niranvv.com/test/php_ajax_input.php

..:: Part 2 Over ::..

Part 3 ( Coming Next ): Displaying the values from the database using php and deleting those values by checking the checkboxes as displayed here: Fun.niranvv.com/test/php_ajax_output.php

Update: Part 3 and Part 4 are integrated here:
Ajax+php+sql=simply Superb!(with Visitor Tracking) :: Section 2 (retrive Values From Database And Dynamic Update!)

All the updates work fine....

Best regards,
Go to the top of the page
 
+Quote Post
musthafa
post Dec 28 2007, 10:41 AM
Post #8


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 1
Joined: 28-December 07
Member No.: 27,190



Superb ....
Go to the top of the page
 
+Quote Post
wutske
post Dec 28 2007, 01:05 PM
Post #9


Way Out Of Control - You need a life :)
Group Icon

Group: [HOSTED]
Posts: 1,043
Joined: 2-August 05
From: Kapellen (Antwerp, Belgium)
Member No.: 7,585



I haven't read the whole tutorial (I don't have much time due to exams rolleyes.gif ), but I'm going to try this one out when I have some spare time to do some programming (probably not until february dry.gif). Looks to be a great tutorial (just the way I like them).

@musthafa: don't forget to read theb board rules wink.gif . Post that only contain 'great', 'super', ... and other 'useless' (they don't have an added value for the post) remarks can be tagged as spam and you'll lose credits for that.

This post has been edited by wutske: Dec 28 2007, 01:06 PM
Go to the top of the page
 
+Quote Post
Miles
post Dec 29 2007, 03:03 PM
Post #10


Advanced Member
Group Icon

Group: [HOSTED]
Posts: 177
Joined: 25-December 07
Member No.: 27,129



Nice tutorial, I've always wondered on how ajax works, and was confused when reading other tutorials, you've really explained this good, hopefully I'll be able to add another programming language to the list of ones that I know!
Go to the top of the page
 
+Quote Post

2 Pages V   1 2 >
Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. CuteNews: PHP-based Blog System - No MySQL(10)
  2. Php Tutorial: Making A Shoutbox(11)
  3. Fake An Ajax Loading Sequence(5)
  4. Ajax(12)