we have created 5 files for fetch record through Ajax from database.
(i) Index.php
(ii) response-file.php
(iii) connection.php
(iv) employee.sql
(v) jquery-1.11.2.min.js
Note:- you can download code from this
(i) index.php:- file which has html form, ajax function and include jquery library file.
Note:- For fetch record, we should use GET method.
<html> <head> <script src="jquery-1.11.2.min.js"></script> <script> function Ajaxfun() { var username = $('#uname').val(); $.ajax({ // The URL for the request url : "response-file.php", // The data to send (will be converted to a query string) data : { uname : username }, // Whether this is a POST or GET request type : "GET", // Code to run if the request succeeds; // the response is passed to the function success : function(response) { //alert(response); $("#ajaxDiv").html(response); }, // Code to run if the request fails; the raw request and // status codes are passed to the function error : function(xhr, status, errorThrown) { alert("Sorry, there was a problem!"); console.log("Error: " + errorThrown); console.log("Status: " + status); console.dir(xhr); }, }); } </script> </head> <body> <form> <div style="width:400px; background-color:#e9eaed"> <div> <div style="float: left;width:30%"> Select Name </div> <div style="float: left;width:70%"> <select name="uname" id="uname"> <option value="">Select Name</option> <option value="John">John</option> <option value="Tony">Tony</option> <option value="Leela">Leela</option> <option value="Robert">Robert</option> </select> </div> </div> <div style="clear: both; height:5px;"></div> <div align="center" onclick="Ajaxfun()"> <input type="button" name="getValue" value="Get Value"/> </div> <div style="clear: both;"></div> <div id="ajaxDiv"></div> </form> </div> </body> </html>
(ii) response-file.php:- which has include database connection file and database query.
<?php include ('connection.php'); $uname = mysql_real_escape_string($_REQUEST['uname']); $errmsg = ""; $err_count = 0; if ($uname == '') { $errmsg .= "Please select the uname"; $err_count++; } if ($err_count == 0) { $query = mysql_query("select * from emp where emp_name='" . $uname . "'"); while ($results = mysql_fetch_assoc($query)) { echo $results['emp_name'] . ' is a ' . $results['emp_desgination'] . ' and monthly income is ' . $results['emp_salary']; } } else { echo $errmsg; } ?>
(iii) connection.php:- which is include in the response-file.php
<?php $host_name = "localhost"; $user_name = "root"; $password = ""; $database_name = "employee"; $conn = mysql_connect($host_name, $user_name, $password); if (!$conn) { die('server is not connect'); } else { mysql_select_db($database_name, $conn); } ?>
(iv) employee.sql:- upload in to mysql-database.
(v) jquery-1.11.2.min.js:- this jquery library include in the index.php file.