Tuesday, September 15, 2015

AJAX - Client Side and Server Side PHP Database Operations


·        AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
·        Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display.
·        Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server.
·        With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
·        XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.
·        AJAX is a web browser technology independent of web server software.
·        A user can continue to use the application while the client program requests information from the server in the background.
·        Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger.
·        Data-driven as opposed to page-driven.
For more guidance on Project !!!

Online Individual / Group classes in English / Sinhala / Tamil. Sample Projects/Assignments Exam Papers, Tutorials, Notes and Answers will we provided.

CALL +94 777 33 7279 | EMAIL  ITCLASSSL@GMAIL.COM

ucsc bit registration 2023 bit (ucsc syllabus) bit colombo university fees bit results bit vle bit course fee bit exam time table 2023 bit moratuwa

Rich Internet Application Technology

AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript, which is hard to maintain and debug.

AJAX is Based on Open Standards

AJAX is based on the following open standards:
  • Browser-based presentation using HTML and Cascading Style Sheets (CSS).
  • Data is stored in XML format and fetched from the server.
  • Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
  • JavaScript to make everything happen.

AJAX - Database Operations
To clearly illustrate how easy it is to access information from a database using AJAX, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, let us do the ground work. Create a table using the following command.
NOTE: We are assuming you have sufficient privilege to perform the following MySQL operations
CREATE TABLE 'ajax_example' (
   'name' varchar(50) NOT NULL,
   'age' int(11) NOT NULL,
   'sex' varchar(1) NOT NULL,
   'wpm' int(11) NOT NULL,
   PRIMARY KEY  ('name')
) 
Now dump the following data into this table using the following SQL statements:
INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);
INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);
INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);
INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);
INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);
INSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90);

Client Side HTML File

Now let us have our client side HTML file, which is ajax.html, and it will have the following code:
<html>
<body>
<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 and will update
   // div section in the same page.
   ajaxRequest.onreadystatechange = function(){
   
      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
      }
   }
   
   // Now get the value from user and pass it to
   // server script.
   var age = document.getElementById('age').value;
   var wpm = document.getElementById('wpm').value;
   var sex = document.getElementById('sex').value;
   var queryString = "?age=" + age ;
   
   queryString +=  "&wpm=" + wpm + "&sex=" + sex;
   ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
   ajaxRequest.send(null); 
}
//-->
</script>
 
<form name='myForm'>
 
   Max Age: <input type='text' id='age' /> <br />
   Max WPM: <input type='text' id='wpm' /> <br />
   Sex: 
   <select id='sex'>
      <option value="m">m</option>
      <option value="f">f</option>
   </select>
   <input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
   
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
NOTE: The way of passing variables in the Query is according to HTTP standard and have formA.
URL?variable1=value1;&variable2=value2;
The above code will give you a screen as given below:
NOTE: This is dummy screen and would not work
Max Age:  
Max WPM: 
Sex:   
Your result will display here in this section after you have made your entry.
NOTE: This is a dummy screen.

Server Side PHP File

Your client-side script is ready. Now, we have to write our server-side script, which will fetch age, wpm, and sex from the database and will send it back to the client. Put the following code into the file "ajax-example.php".
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
         
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
         
//Select Database
mysql_select_db($dbname) or die(mysql_error());
         
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
         
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
         
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
 
if(is_numeric($age))
   $query .= " AND age <= $age";
 
if(is_numeric($wpm))
   $query .= " AND wpm <= $wpm";
         
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
 
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
 
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
   $display_string .= "<tr>";
   $display_string .= "<td>$row[name]</td>";
   $display_string .= "<td>$row[age]</td>";
   $display_string .= "<td>$row[sex]</td>";
   $display_string .= "<td>$row[wpm]</td>";
   $display_string .= "</tr>";
}
 
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
 
echo $display_string;
?>
Now try by entering a valid value (e.g., 120) in Max Age or any other box and then click Query MySQL button.
Max Age:  
Max WPM: 
Sex:   
Your result will display here in this section after you have made your entry.
If you have successfully completed this lesson, then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write AJAX applications.

AJAX can be used for interactive communication with a database.



AJAX Database Example

The following example will demonstrate how a web page can fetch information from a database with AJAX:

Example

     

Person info will be listed here...

Example Explained - The MySQL Database

The database table we use in the example above looks like this:
id
FirstName
LastName
Age
Hometown
Job
1
Peter
Griffin
41
Quahog
Brewery
2
Lois
Griffin
40
Newport
Piano Teacher
3
Joseph
Swanson
39
Quahog
Police Officer
4
Glenn
Quagmire
41
Quahog
Pilot

Example Explained

In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.
The function is triggered by the onchange event.
Here is the HTML code:

Example

<html>
<head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>
Code explanation:
First, check if no person is selected (str == ""). If no person is selected, clear the content of the txtHint placeholder and exit the function.
If a person is selected, do the following:
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an HTML table:
<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";
    echo "<td>" . $row['Job'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
  1. PHP opens a connection to a MySQL server
  2. The correct person is found
  3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder
The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web 2.0 in 2005 became popular.
XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side.
The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.
You already have seen a couple of examples on how to create an XMLHttpRequest object.
Listed below is listed are some of the methods and properties that you have to get familiar with.


XMLHttpRequest Methods

  • abort()
Cancels the current request.
  • getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
  • getResponseHeader( headerName )
Returns the value of the specified HTTP header.
  • open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications) may be possible.
The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
  • send( content )
Sends the request.
·        setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties

  • onreadystatechange
An event handler for an event that fires at every state change.
  • readyState
The readyState property defines the current state of the XMLHttpRequest object.
The following table provides a list of the possible values for the readyState property:
State
Description
0
The request is not initialized.
1
The request has been set up.
2
The request has been sent.
3
The request is in process.
4
The request is completed.
readyState = 0 After you have created the XMLHttpRequest object, but before you have called the open() method.
readyState = 1 After you have called the open() method, but before you have called send().
readyState = 2 After you have called send().
readyState = 3 After the browser has established a communication with the server, but before the server has completed the response.
readyState = 4 After the request has been completed, and the response data has been completely received from the server.
  • responseText
Returns the response as a string.
  • responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties.
  • status
Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").
  • statusText
Returns the status as a string (e.g., "Not Found" or "OK").

AJAX Security: Server Side

·        AJAX-based Web applications use the same server-side security schemes of regular Web applications.
·        You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programmatic).
·        AJAX-based Web applications are subject to the same security threats as regular Web applications.

AJAX Security: Client Side

·        JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-side weaknesses.
·        JavaScript code is downloaded from the server and executed ("eval") at the client and can compromise the client by mal-intended code.
·        Downloaded JavaScript code is constrained by the sand-box security model and can be relaxed for signed JavaScript.


Ref

php about page
php about us page
php about blank
php about information
php about login script
php about data
php about class
about.php cartid=
about php language
about php developer
php above html
php above document root
php directory above
php folder above
php folder above document root
php dir above
php include above root
php echo above
php files above root
php require directory above
php session across pages
php session across subdomains
php variable across files
php variable across pages
php string across multiple lines
php session across domains
php variable across sessions
php singleton across requests
php session across multiple servers
php variable across functions
php after submit redirect page
php after function
php after page load
php after string
php after foreach
php after last slash
php after insert get id
php after time
php after login display username
php after rehab
php against usd
php against sql injection
php against xss
php against
php against eur
php match against
php authenticate against active directory
php check against regex
php protect against brute force
php authenticate against adfs
php round 2 decimal
php round up
php round down
php round off
php round to nearest 10
php round to nearest 5
php round not working
php round number up
php round up always
php round number to 2 decimals
php as backend
php as string
php as a service
php as key value
php as cgi
php as keyword
php as array
php as int
php as a general purpose language
php as number
php at symbol
php at sign
php at operator
php at command
php at facebook
php at w3schools
php at sign before function
php at symbol before variable
php at symbol before function
php at sign operator
php before function
php before or after html
php before javascript
php before date
php before submit
php before html
php before exit
php before type
php before construct
php before doctype
php behind proxy
php behind reverse proxy
php behind the parser
php behind
php behind proxy server
php code behind
php composer behind proxy
php curl behind proxy
php look behind
php copy behind proxy
php below the fold
php round below
php function below
php extensions listed below are installed
phones below php 10000
php memory limit below 128mb
php between dates
php between operator
php between condition
php between time
php between query
php between html
php between function
php between range
php between hours
php between two strings
php beyond the web
php beyond the web pdf
php beyond the basics
lynda php beyond the basics
php date beyond 2038
php with mysql beyond the basics with kevin skoglund
php with mysql beyond the basics download
php with mysql beyond the basics exercise files
php with mysql beyond the basics with kevin skoglund download
php but
php empty but not zero
php explode but keep delimiter
php installed but not working
php return but continue execution
php isset but null
php sort but keep keys
php foreach but not last
php redirect but keep url
php-mbstring but it is not installable
php by reference
php by w3school
php by javatpoint
php by example
php by przemo
php by saurabh shukla
php by reference or value
php by jon duckett
php by example book
php by value
php come funziona
php come iniziare
php come andare a capo
php code from url
php come richiamare una funzione
does php come with apache
when did php come out
facebook.com.php
file php come si aprono
file php come si apre
php download
php download file
php download for windows
php download file from server
php download file from url
php download image
php download file script
php download csv
php download pdf
php download zip file
php echo during execution
php unset during foreach
php echo during loop
php output during loop
php error during session start
php redirect during ajax call
php error during upload
php issues during installation
php flush output during execution
php modify array during foreach
php except array
php except
php except notice
except php mysql
php try except
php foreach except last
php foreach except first
php lowercase except first letter
php foreach except
php implode except last
php for loop
php for beginners
php foreach
php for windows
php for loop array
php for beginners pdf
php for dummies
php for mac
php for wordpress
php for loop array length
php from beginning
php from scratch
php from command line
php from json
php from terminal
php from string to array
php from header
php from javascript
php from html
php form validation
php in array
php in sinhala
php in html
php in w3school
php in javascript
php in tamil
php in 2019
php in visual studio
php in ubuntu
php in netbeans
php inside javascript
php inside html
php inside javascript function
php inside html tag
php inside jquery
php inside php
php inside javascript file
php inside css
php inside html file
php inside style tag
php into lkr
php into usd
php into inr
php into pkr
php into html
php into gbp
php into aud
php into aed
php into javascript
php into pounds
php less than or equal to
php less compiler
php less than or greater than
php less than equal
php less than and greater than
php less than negative number
php less
php less parser
php like string
php like query
php like operator
php like button
php like system
php like languages
php like function
php like search
php like sql
php like mysql
php mid string
php mid michigan
php mid string function
php mid level interview questions
php mid str
php mid michigan providers
php mid exam
php mid michigan insurance
php mid night
php midnight date
php minus 1 day
php minus 1
php minus days from date
php minus 1 month
php minus date
php minus 1 year
php minus equals
php minus time
php minus operator
php minus hours
php near me
php classes near me
php programs near me
php jobs near me
php coaching near me
php institute near me
php agency near me
php course near me
php developer near me
adolescent php near me
php of alabama
php of michigan
php of the carolinas
php of northern indiana
php of north carolina
php of alabama dothan al
php of glastonbury
php of ca
php of northern
php of mi
php off error reporting
php off warning
php off notice
php off
php off all errors
php on local server
off php version
php turn off error reporting
php turn off warnings
php on iis
php on windows
php on mac
php on button click
php onclick
php on ubuntu
php on linux
php on aws
php on windows 10
php on nginx
php add on top of array
php push on top of array
php echo on top
php put on top of array
php top frameworks
php top frameworks 2018
php top interview questions
php top frameworks 2017
php top
php top tails
php opposite of explode
php opposite of isset
php opposite of compact
php opposite of extract
php opposite of strtotime
php opposite of http_build_query
php opposite of array_intersect
php opposite of htmlspecialchars
php opposite of nl2br
php opposite of empty
php out of memory
php out parameter
php out of memory exception
php out of date
php out of memory (allocated
php out of memory tried to allocate
php out variable
php out of memory error handling
php out to file
php out of bounds exception
php outside html
php outside variable in function
php outside document root
php outside wordpress
php outside directory
php outside of public_html
php outside variables
outside php
php const outside class
php include outside folder
php over python
php over html
php over java
php over javascript
php over iis
php over node js
php over asp and jsp
php over asp.net
php over_query_limit
php over .net
php past papers
php past date
php last year
php past present and future
php last query
php last 3 months
php date past or future
php get last month
php datetime past
php get past date
php per usd
php per kwh
php per year
php per dollar
php per kwh meralco
php per hour rate
php per page
php per hour
php per
php per watt
php plus equals
php plus one
php plus 1 day
php plus array
php plus equals string
php plus date
php plus 1 month
php plus sign
php plus string
php plus days
php post request
php post method
php post example
php post form
php post json
php post not getting values
php post to url
php post array
php post data
php post max size
php pre tag
php pre print_r
php pre increment
php pre select dropdown
php pre match
php pre commit hook
php pre var_dump
php pre echo
php predefined functions
php pre compiler
php pro bid
php pro bid v8
php pro and cons
php pro bid v8 nulled
php pro tips
php pro bid v7
php pro bid v7.3 nulled
php pro bid nulled
php pro t fusion
hp probook
php @since
php since date
phpdoc @since
php days since date
php seconds since epoch
php milliseconds since epoch
php seconds since midnight
php years since date
php days since epoch
php months since date
php then function
php then
php then statement
php than
php then else
php greater than
php bigger than
php more than one constructor
php greater than not working
php faster than python
php through proxy
php throw exception
php through array
php through command line
php loop through associative array
php loop through object
php loop through json
php loop through json object
php loop through multidimensional array
php loop through object properties
php till sek
php till kr
php till svenska kronor
php till kronor
php till skr
euro to php
php substring till character
php wait till exec is finished
php days till date
php substr till end
php to lkr
php to usd
php to string
php to lowercase
php to gbp
php to uppercase
php to pdf
php to aud
php to html
php to int
php under the hood
php under construction template
php under iis
php under construction page
php under control
php under windows
html and php
javascript and php
run php under different user
php comes under which technology
php unlike
unlink function in php
php like unlike
php until loop
php until loop example
php until true
php substring until character
php days until date
php wait until function completes
php wait until file exists
php pause until keypress
php loop until true
php wait until exec finished
php up one directory
php up first letter
php up memory limit
php up two directories
php up case
php up arrow
php up round
up.php malware
up.php shell
popup in php
php redirect upon login
php stratford upon avon
php refresh page on submit
php success message on submission
php logout on inactivity
php array upside down
php image upload upside down
upside php
php versus python
php versus javascript
php versus java
php versus html
php versus .net
php versus ruby
php versus c#
php vs usd
php versus node.js
php via command line
php_via_fastcgi
php_via_fastcgi http error 500.0
php_via_fastcgi has a bad module fastcgimodule
php_via_fastcgi iis
php via proxy
php_via_fastcgi has a bad module
php via cgi
php_via_fastcgi error
php via
php vs javascript
php vs java
php vs python
php vs html
php vs asp.net
php vs c#
php vs ruby
php with mysql
php with firebase
php with html
php with ajax
php with xampp
php with laravel for beginners
php with sql server
php with mongodb
php with react
php with javascript
php within html
php within javascript
php within php
php within javascript function
php within script tag
php within jquery
php within html tag
php within string
php within range
php within js file
php without framework
php without apache
php without xampp
php without composer
php without extension
php without html
php without php
php without database
php without reloading page
php without semicolon
php worth learning
php worth learning 2019
php agency worth
php net worth
500 php worth of gift
300 php worth of gift
is php worth learning reddit
php fort worth
php certification worth it
php group net worth