Here’s a simple example of using AJAX with PHP to demonstrate how to send data from the front end to the back end and fetch a response from the server without reloading the page.
Overview
Front-end (HTML + jQuery): A form to submit data via AJAX.
Back-end (PHP): A PHP script that processes the data and returns a response.
In this example, we create two files
- index.php, which is a client-side file.
- ajax_results.php, which is a server-side file.
In index.php file
<html>
<head>
<script>
function Ajaxfun()
{
var ajaxRequest; // The variable that makes Ajax possible!
try{// Opera 8.0+, Firefox,
SafariajaxRequest = new XMLHttpRequest();
} catch (e){// Internet Explorer Browserstry
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){// Something went wrongalert("Your browser broke!");return false;
}}
}
/ Now get the value from user name, user sex and pass it to
// server script.
var uname = document.getElementById('uname').value;
var usex = document.getElementById('usex').value;
var queryString = "?uname=" + uname ;
queryString += "&usex=" + usex;
ajaxRequest.open("GET", “ajax-results.php” + queryString, true);
ajaxRequest.send(null);
// Create a function that will receive data
// sent from the server and will show data on the ajax div.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById(‘ajaxDiv’);
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
}</script>
</head>
<body>
<form>
<div>
<div style=”float: left;width:30%”>
Your Name
</div>
<div style="float: left;width:70%">
<input type="text" id=”uname” />
</div>
</div>
<div>
<div style="float: left;width:30%">
Your Sex
</div>
<div style="float: left;width:70%”>
<select name="usex" id="usex">
<option value="">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div style="clear: both"></div>
<div align="center" onClick="Ajaxfun()">
<span style="background-color:#3a5795; color:#fff; cursor: pointer;">Get</span>
</div>
<div style="clear: both"></div>
<div id="ajaxDiv"></div>
</form>
</body>
</html>
In ajax_request.php
<?php
$uname=$_REQUEST['uname'];
$usex=$_REQUEST['usex'];
$errmsg="";
$err_count=0;
if($uname==''){
$errmsg .="Please write the name";$err_count++;
}
if($usex ==''){$errmsg .="Please select the sex";$err_count++;}
if($err_count==0){
echo "Hi, your name is $uname and sex is $usex";
}else{
echo $errmsg;
}?>
Output: