Pages

Wednesday, July 11, 2012

Insert using Ajax Data Demo

Create a php document name it add_record.php

<?php

class InsertData
{
    private $fname, $lname, $phone, $email_address;
   
    #This is the class constructor
    public function __construct($fname, $lname, $phone, $email_address)
    {
        $this->fname = $fname;
        $this->lname = $lname;
        $this->phone = $phone;
        $this->email_address = $email_address;
        $this->insertQuery(); //Instanciating the object will automatically call the insert statement
    }
   
    public function insertQuery()
    {
        $sql = "INSERT INTO address_bk(fname, lname, phone, email_address)
            VALUES('$this->fname', '$this->lname', '$this->phone', '$this->email_address')";
        $result = mysql_query($sql);
        //If record has been successfully added
        if($result)
        {
            echo "Contact has been successfully added";
        }
        else
        {
            echo "Error! Inserting new contact";
        }
    }
}

    include_once 'connection.php';
   
    //Instantiate the class(InsertData class call)
    new InsertData($_GET['fname'], $_GET['lname'], $_GET['phone'], $_GET['email']);
   
    //Close connection after transaction
    mysql_close($server_connect);

?>


Create a javaScript file and name it ajax_add.js


var xmlHttp = createXMLHttpRequest();

function createXMLHttpRequest()
{
    if(window.ActiveXObject)
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }
}

function handleStateChange()
{
    if(xmlHttp.readyState == 4)
    {
        if(xmlHttp.status == 200)
        {
            document.getElementById('content').innerHTML = xmlHttp.responseText;
        }
    }
}

function submitData()
{
    var fname = document.getElementById('fname_post').value;
    var lname = document.getElementById('lname_post').value;
    var phone = document.getElementById('phone_post').value;
    var email = document.getElementById('email_post').value;
    var url = "http://localhost/samples/add_record.php?fname=" + escape(fname) + "&lname=" + escape(lname) + "&phone=" + escape(phone) + "&email=" + escape(email);
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.send(null);
    xmlHttp.close();   
}

Create a html file and name it add_record.html



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert using Ajax Data Demo</title>
<script type="text/javascript" src="ajax_add.js"></script>
</head>
<body>
<h2>Insert using Ajax Data Demo</h2>
    <table>
        <tr>
            <td>Firstname</td>
            <td><input type="text" id="fname_post" value="" /></td>
        </tr>
        <tr>
            <td>Lastname</td>
            <td><input type="text" id="lname_post" value="" /></td>
        </tr>
        <tr>
            <td>Phone number</td>
            <td><input type="text" id="phone_post" value="" /></td>
        </tr>
        <tr>
            <td>Email Address</td>
            <td><input type="text" id="email_post" value="" /></td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" value="Add Contact" onClick="submitData()" />
            </td>
        </tr>
    </table>
    <div id="content">
    </div>
</body>
</html>

As you can see from the above page display, the page is rendered through a html page. The ajax script is responsible for routing requests to the php server side script.

The figure below represents the database table structure.

An Ajax basic sample Demo

Create a html document and save it as ajax_test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>An Ajax basic sample Demo</title>

<!--Get Ajax objects from remote file-->
<script type="text/javascript" src="ajax_script.js"></script>
<style>
    #display{ color: #09F; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 16px;}
</style>
</head>

<body>
<h2>An Ajax basic sample Demo</h2>

<button onclick="displayBlogName();">Display Blog name</button>
<br /><br />

<!--This div will render what has been typed by the use-->
<div id="display">
</div>

</body>
</html>

Create another file and save it as site_name.html. Save it in the same folder too.

<p>http://phpcodesamples.blogspot.com/</p>

Finally create an JavaScript file and name it ajax_script.js

// JavaScript Document

var xmlHttp = createXMLHttpRequest();

function createXMLHttpRequest()
{
    //Allow Ajax to work with Internet Explorer by using ActiveXObjects
    if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }
}

function handleStateChange()
{
    if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
            document.getElementById('display').innerHTML = xmlHttp.responseText;
        }
    }
}


function displayBlogName()
{   
    //The url responsible for the data feed or processing
    var url = "http://localhost/samples/site_name.html";
    //Open the request Object
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = handleStateChange;
    //Send your request to the server
    xmlHttp.send(null);
    xmlHttp.close();
}

  As you will notice when you load ajax_test.html in your browser. The page will display the message in the site_name.html without conducting any page reload. This is the feature I was explaining earlier when introducing Ajax. I will be showing how the same can be achieved using PHP.


Tuesday, July 10, 2012

Ajax Integration

Ajax Integration

As you can see our page loads in the examples we have been dealing with have often entailed that the entire page reloads upon performing a new request such as adding a new data and displaying a new search result. There is a problem with relying on page loading entirely on php scripts. For one this is very slow since with each new request all html objects have to be reloaded again. Furthermore operations such as deleting data and updating new records that affect a single field in a set of large data list will be challenging (that is why updating and deleting samples will be introduced after illustrating the Ajax concept). All this makes it worthwhile for every developer coding server side scripting such as JSP (Java Server Pages) ASP.NET or PHP incorporate AJAX.

Many examples that have advanced the popularity of the AJAX in rendering content have been seen in major websites such as Facebook, Gmail and twitter. Powerful abstraction can also be rendered through libraries such as JSON and JQuery which have AJAX objects already set up. The use of Ajax has greatly improved on web content dynamism as well as usability in general. I will be introducing Ajax in bits by creating simple examples and later bring out the relationship of integrating it with PHP. I hope you will enjoy. :-)

Code List
  • An Ajax basic sample 
  • Separating php codes, html pages and ajax 
  •  Ajax and php Insert example 
  • Ajax and php delete example 
  • Ajax and php edit example
·      
·         
·         

Conducting a search Query


<?php

/*

    I have assumed you have created a database with a table named address_bk
    It should have the following fields:
    id: int(3) Set as primary
    fname: VARCHAR(20)
    lname: VARCHAR(20)
    phone: VARCHAR(10)
    email_address: VARCHAR(30)
    NB: This table will be used for the next several code samples
    Reach me at: allan.koskei@gmail.com
  
*/

class SearchContact
{
  
    //The user will be conducting search based on the first name
    private $fname;
  
    //Class constructor
    public function __construct($fname)
    {
        $this->fname = $fname;
        $this->searchQuery();
    }
  
    public function searchQuery()
    {
        //The '%$this->fname%' is a wildcard search that brings results corresponding to the inputed search item
        $sql = "SELECT * FROM address_bk WHERE fname LIKE '%$this->fname%'";
        $result = mysql_query($sql);
        $num_rows = mysql_num_rows($result);
      
        //If the query is working
        if($result){
            //If results exists
            if($num_rows > 0){
                ?>
                <table>
                    <tr>
                        <td><b>Firstname</b></td>
                        <td><b>Lastname</b></td>
                        <td><b>Phone number</b></td>
                        <td><b>Email Address</b></td>
                    </tr>
                <?php
                while($db_field = mysql_fetch_assoc($result)){
                    ?>
                    <tr bgcolor="#F2F2F2">
                        <td><?php echo $db_field['fname']; ?></td>
                        <td><?php echo $db_field['lname']; ?></td>
                        <td><?php echo $db_field['phone']; ?></td>
                        <td><?php echo $db_field['email_address']; ?></td>
                    </tr>  
                    <?php              
                }
                ?>
                </table>
                <?php
            }
            //If results doesn't exists
            else{
                echo "$this->fname does not exist!";
            }
        }
        //If the query fails or the connection fails
        else{          
            echo 'Error fetching data';
        }
    }
}


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search Contact Demo</title>
</head>

<body>
<h2>Search by name Demo</h2>
<form method="post" action="<?php $_SERVER['PHP_SELF']?>">
    <input type="text" name="fname_post" value="" />
    <input type="submit" value="Search Contact" />
</form>
<br /><br />
<!--I have placed the php code here so that the results will be displayed under the search textbox-->
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
    include_once 'connection.php';
    new SearchContact($_POST['fname_post']);
    mysql_close($server_connect);
}
?>

</body>
</html>

Inserting data into a database table

This script is a simple code that inserts data into a database. Save this file as add_record.php. However ensure it is saved in the same folder with the connection.php file. Run your file through the browser. I have used an object oriented approach in a simple manner to introduce any beginner of OOP.
<?php

/*

    I have assumed you have created a database with a table named address_bk
    It should have the following fields:
    id: int(3) Set as primary
    fname: VARCHAR(20)
    lname: VARCHAR(20)
    phone: VARCHAR(10)
    email_address: VARCHAR(30)
    NB: This table will be used for the next several code samples
    Reach me at: allan.koskei@gmail.com
   
*/

class InsertData
{
   
    private $fname, $lname, $phone, $email_address;
   
    #This is the class constructor
    public function __construct($fname, $lname, $phone, $email_address)
    {
        $this->fname = $fname;
        $this->lname = $lname;
        $this->phone = $phone;
        $this->email_address = $email_address;
        $this->insertQuery(); //Instanciating the object will automatically call the insert statement
    }
   
    public function insertQuery()
    {
        $sql = "INSERT INTO address_bk(fname, lname, phone, email_address)
            VALUES('$this->fname', '$this->lname', '$this->phone', '$this->email_address')";
        $result = mysql_query($sql);
        //If record has been successfully added
        if($result){
            echo "Contact has been successfully added";
        }
        else{
            echo "Error! Inserting new contact";
        }
    }
}

//If the form submit button has been clicked

if($_SERVER['REQUEST_METHOD']=='POST')
{
    include_once 'connection.php';
   
    //Instantiate the class(InsertData class call)
    new InsertData($_POST['fname_post'], $_POST['lname_post'], $_POST['phone_post'], $_POST['email_post']);
   
    //Close connection after transaction
    mysql_close($server_connect);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert Data Demo</title>
</head>
<body>
<h2>Insert Data Demo</h2>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
    <table>
        <tr>
            <td>Firstname</td>
            <td><input type="text" name="fname_post" value="" /></td>
        </tr>
        <tr>
            <td>Lastname</td>
            <td><input type="text" name="lname_post" value="" /></td>
        </tr>
        <tr>
            <td>Phone number</td>
            <td><input type="text" name="phone_post" value="" /></td>
        </tr>
        <tr>
            <td>Email Address</td>
            <td><input type="text" name="email_post" value="" /></td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" value="Add Contact" name="submit_data" />
                <input type="reset" value="Clear" name="clear_date" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>



Connecting to the server and selecting a database

The addition to the new function mysql_select_db('address_db') facilitates connection to a database. In this case the database I created bears the name address_db.Though you are free to use any of your choice.

<?php

$server_connect = @mysql_connect('localhost', 'root', '');
$database_select = @mysql_select_db('address_db');

//If server connection fails
if(!$server_connect){
    echo 'Server connection Error!<br />';
}

//If database connection fails
if(!$database_select){
    echo 'Database connection Error!';
}
?>

Save it as connection.php. And run it through your localhost

Sunday, July 8, 2012

Connecting to server

This code connects to a server


<?php

$server_connect = mysql_connect("localhost", "root", "");

if(!$server_connect){
       echo "Server connection error!";

}
else{
      echo "Connection has been established";

}
?>