PHP & Ajax
INTRODUCTION : AJAX stands for Asynchronous Javascript and XML. AJAX is used to make web pages more fast, interactive and dynamic. AJAX helps to update some parts of the page without reloading the whole page. Conventional technique uses synchronous methods to transfer information from and to the server. AJAX uses:
XMLHttpRequest
object : for exchanging data asynchronously.- JavaScript/DOM: for displaying data or to interact with information.
- CSS: to style the data.
- XML : format for transferring the data.
AJAX WITH PHP : We are using an example displaying States according to selected Country using AJAX along with PHP in order to demonstrate how a web server communicates with a web page.
STEP - I: Create MySQL tables |
|
|
STEP - II: Insert values into tables accordingly. For example: |
|
|
STEP - III: Considering the filename as |
|
ajax_process.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// Creating connection
$conn = mysqli_connect($server, $username, $password, "mydb");
if (!$conn) {
die(mysqli_connect_error());
}
$statesArr = array();
$sql = "SELECT * FROM states WHERE country_id = '".$_POST['countryID']."'";
$exe = mysqli_query($conn, $sql) or die("SQL Error");
if (mysqli_num_rows($exe) > 0) {
while($row = mysqli_fetch_assoc($exe)) {
$arr['id'] = $row['id'];
$arr['name'] = $row['name'];
$statesArr[] = $arr;
}
}else{
$statesArr = array();
}
die(json_encode($statesArr));
?>