JQuery AJAX Example With PHP MySQL
JQuery AJAX Example With PHP MySQL
jQuery is a light weight JavaScript library and has wide range of plugins available for
doing different tasks very easily. jQuery hides complexities of plain JavaScript and
provides a quick way to perform different tasks. It has several methods that are used
to perform AJAX requests.
$.getJSON – This method get JSON encoded data using AJAX HTTP GET request
$.post – This method load data from server using AJAX HTTP POST request.
Using jQuery, AJAX GET request can fetch data from server. The task we are going
to do is fetch users from MySQL database using jQuery AJAX.
1. Create a MySQL table and insert data
2. Create HTML form and jQuery script to perform AJAX GET Request to PHP
MySQL Server
3. Write a PHP script to receive request from client and fetch data from MySQL
database and send a JSON encoded result to client
Now I hope you have already installed PHP, Apache, MySQL on your system using
WAMP, XAMPP or MAMP.
1. Create folder for the project name ajaxjquery inside your root directory.
4. When user will click on a button an AJAX request will be posted to PHP MySQL
server.
5. PHP MySQL will return JSON encoded result back to client end.
<html>
<head>
</head>
<body>
<div id="records"></div>
<p>
<input type=”button” id = "getusers" value = "Get Users" />
</p>
</div>
<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>
<script type=”text/javascript”>
.done(function( data ) {
var result = $.parseJSON(data);
$("#records").html(string);
});
});
});
</script>
</body>
</html>
In HTML code we create a button. Button’s onclick method will perform a GET
request and will embed the result to a div.
jQuery $function()
Inside first script tag we called jQuery from jQuery CDN so we can perform an AJAX
request. In second script tag we have a code block inside
$(function(){
The code above is a jQuery code snippet that make sure the code inside this block
executes after whole page is loaded. The next code snippet
$("#getusers").on('click', function(){
$.ajax({
method: "GET", url: "getrecords.php",
}).done(function( data ) {
string += "<tr>
<td>"+value['id'] + "</td>
<td> " + value['first_name']+' '+value['last_name']+'</td>
<td> '+ value['email']+"</td>
</tr>";
});
string += '</table>';
$("#records").html(string);
});
In the script above when a user clicks on the button whose id is #getusers . An AJAX
request is posted to a PHP page named getrecords.php. PHP page returns a JSON
Encoded result. Using jQuery’s method $.parseJSON result is decoded and a loop is
performed through data array. Inside loop user information is concatenated inside a
table and then all the records are appended to a div using HTMLmethod in jQuery.
In this last step we have to create a PHP script that will accept a request and send back
JSON encoded result. So following are steps.
3. After query execution encode the results in a JSON array and return back to client.
Database connection
$host = "localhost";
$username = "root";
$password = "";
$dbname = "dbusers";
$result_array = array();
/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection */
if ($conn->connect_error) {
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
$conn->close();
?>
In this article we have explored jQuery’s AJAX GET method to fetch results from
Server.
2. Add HTML code that will display form fields with a button.
3. When user fills in the form and clicks on button an AJAX POST request is sent to
server.
<head>
<title>jQuery AJAX POST Example</title>
</head>
<body>
<p>
<strong>Please fill in the form and click save.</strong>
</p>
<div id = "container" >
<div id="message"></div>
<p>
<form name='form1'>
<label>First Name:</label>
<input type='text' placeholder='First Name' name='first_name' id=
'first_name' required ><br />
<label>Last Name:</label>
<label>Email:</label>
</form>
</p>
</div>
<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>
<script type=”text/javascript”>
$(function(){
$("#saveusers").on('click', function(){
$.ajax({
method: "POST",
url: "saverecords.php",
}).done(function( data ) {
var result = $.parseJSON(data);
if(result == 1) {
} else{
str = 'User data could not be saved. Please try again';
}
$("#message").css('color', 'red').html(str);
});
});
</script>
</body>
</html>
In the form tag we have created text boxes for first_name, last_name and email. New
HTML5 attributes such as placehoder (Used to show a text to user inside text filed,
This text disappears as user starts typing) and required (Used to validate so field is
not empty) are used.
In HTML5 some new elements are also introduced like email. Email type will force
user to enter a valid email address.
Below the form code there is <script> tag to include jQuery. In next <script> there is
a function that executes on onclick event of button with id saveusers.
1. event (click)
2. callback function. When user will click on button, callback function executes. In
function get values of first name, last name and email using val() function in jQuery
and save in variables.
We create a connection to MySQL server, get data from client side and finally after
validations, save data to database. In newer PHP versions mysql_* functions are
deprecated.
Now mysqli or PDO functions are used, these newer functions provide prepared
statements for preventing sql injection attacks.
Data validation
We have to perform server side validation as well. If any of the text box in form was
empty, we have to show user an error message by sending $result value as 2, We
create an prepared statement for insert and bind the parameters. After query
execution success result is sent back to client end.
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$result = 0;
/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection */
if ($conn->connect_error) {
die("Connection to database failed: " . $conn->connect_error);
}
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email'];
$result = 2;
$result = 3;
}else {
$stmt = $conn->prepare($sql);
if($stmt->execute()){
$result = 1;
echo $result;
$conn->close();
Summary
Please leave your comments and feedback below. To keep yourself updated please
subscribe to our newsletter.
Drop down - get value from database set
option to selected
<?php
?>
<form>
<select id="company" name="company">
<option <?php if ($company == 1 ) echo 'selected' ; ?>
value="1">Apple</option>
<option <?php if ($company == 2 ) echo 'selected' ; ?>
value="2">Samsung</option>
<option <?php if ($company == 3 ) echo 'selected' ; ?>
value="3">HTC</option>
</select>
</form>
I couldn't find any solution for this. I need to get the database value ("Default") as the pre-
selected value of the drop down list.
//db connection
mysql_connect("localhost","user","password");
mysql_select_db("database");
//query
$sql=mysql_query("SELECT id,name FROM table");
if(mysql_num_rows($sql)){
$select= '<select name="select">';
while($rs=mysql_fetch_array($sql)){
$select.='<option value="'.$rs['id'].'">'.$rs['name'].'</option>';
}
}
$select.='</select>';
echo $select;
using if condition you can check the first value or currently added value selected
</div>
</head>
<body>
<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>
One more way to do it (if you use form), note that input type is button
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
But you can do it even without form:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
Here you can use either submit or button:
return false;
from JavaScript function for neither of those two examples.
This works.
<html>
<head>
<script type = "text/javascript">
function write_below(form)
{
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML="Your input was:"+input;
return false;
}
</script>
</head>
<html>
<body>
<!-- Trigger/Open The Modal -->
<div style="background-color:#0F0F8C ;height:45px">
<h2 style="color: white">LOGO</h2>
</div>
<div>
<button id="myBtn"> + Add Task  </button>
</div>
<div>
<table id="tasksTable">
<thead>
<tr style="background-color:rgba(201, 196, 196, 0.86)">
<th style="width: 150px;">Name</th>
<th style="width: 250px;">Desc</th>
<th style="width: 120px">Date</th>
<th style="width: 120px class=fa fa-trash"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<div class="modal-header">
<span class="close">×</span>
<h3> Add Task</h3>
</div>
<div class="modal-body">
<table style="padding: 28px 50px">
<tr>
<td style="width:150px">Name:</td>
<td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>
</tr>
<tr>
<td>
Desc:
</td>
<td>
<textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>
<br>
<br>
<br>
</div>
</div>
</div>
<script>
var tasks = [];
var descs = [];
function getDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
</html>
Javascript dropdownlist
Javascript Combobox
A dropdown list provides a method of selecting only one option from a lots of options while only
using up as much space as a single option except while a selection is being made.
Source Code
<html>
<body>
<select id="colors">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
</select>
</body>
</html>
Source Code
<html>
<head>
<script type="text/javascript">
function findDay()
{
var eID = document.getElementById("daysCombo");
var dayVal = eID.options[eID.selectedIndex].value;
var daytxt = eID.options[eID.selectedIndex].text;
alert("Selected Item " + daytxt + ", Value " + dayVal);
}
</script>
</head>
<body>
<select id="daysCombo">
<option value="1">Sunday</option>
<option value="2" selected="selected">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<br><br>
<button onclick="findDay()">Get Selected Day</button>
</body>
</html>
Also the following code will help you to select item from selection option by index number.
document.getElementById("daysCombo").options.item(6).text;
White
Change my color
Source Code
<html>
<head>
<script type="text/javascript">
function changeColor() {
var eID = document.getElementById("colors");
var colorVal = eID.options[eID.selectedIndex].value;
var colortxt = eID.options[eID.selectedIndex].text;
document.getElementById('colorDiv').style.background=colortxt;
}
</script>
</head>
<body>
<select id="colors" onchange="changeColor()">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3" >Green</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
<option value="6" selected="selected">White</option>
</select>
<br><br>
<div id="colorDiv" style="width:200px;height:50px;border:1px solid black;">
Change my color
</div>
</body>
</html>
When you click the button, you can see the color "Orange" is selected.
Source Code
<html>
<head>
<script type="text/javascript">
function changeSelection()
{
var eID = document.getElementById("colors");
eID.options[4].selected="true";
}
</script>
</head>
<body>
<select id="colors">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
</select>
<br><br>
<button onclick="changeSelection()">Set selected value</button>
</body>
</html>
Your inline onchange event on the HTML element limits you, and you currently have to pass lots of
stuff to it.
Instead of that, leave the select element just as a select element itself:
And use scripting to attach the onchange event. The benefit of doing that is that the this keyword
now automatically refers to the element that triggered the event, and from there you can easily get to
the form, and other named elements of the form.
<html>
<head>
</head>
<body>
<form id="taxDetails">
<select name="province" onchange="setTax(document.Form, this.value);">
<option value="">Select Province from List...</option>
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="ON">Ontario</option>
</select>
<input name="showtax" type="text" id="showtax" value="<show-value-of-tax-
here" />
</form>
<script>
var taxCodes = {
'AB': 5,
'BC': 12,
'ON': 13
};
var form = document.getElementById('taxDetails');
form.elements.province.onchange = function () {
var form = this.form;
form.elements.showtax.value = taxCodes[this.value];
};
</script>
</body>
</html>
This tutorial enables you to create sessions in PHP via Login form and web
server respond according to his/her request.
<?php
session_start();
// Do Something
?>
session_start();
<?php
session_start();
echo $_SESSION['login_user'];
<?php
//Or
if(isset($_SESSION['id']))
In our example, we have a login form when user fills up required fields and
press login button, a session will be created on server which assigns him a
unique ID and stores user information for later use.
Watch out live demo or download the given codes to use it.
if(isset($_SESSION['login_user'])){
header("location: profile.php");
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="main">
<div id="login">
<h2>Login Form</h2>
<label>UserName :</label>
<label>Password :</label>
</form>
</div>
</div>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
else
$username=$_POST['username'];
$password=$_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$rows = mysql_num_rows($query);
if ($rows == 1) {
} else {
?>
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="profile">
</div>
</body>
</html>
<?php
// Selecting Database
// Storing Session
$user_check=$_SESSION['login_user'];
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
}
?>
<?php
session_start();
?>
)
CSS File: style.css
@import http://fonts.googleapis.com/css?family=Raleway;
/*----------------------------------------------
------------------------------------------------*/
#main {
width:960px;
margin:50px auto;
font-family:raleway
span {
color:red
h2 {
background-color:#FEFFED;
text-align:center;
border-radius:10px 10px 0 0;
margin:-10px -40px;
padding:15px
hr {
border:0;
margin:10px -40px;
margin-bottom:30px
}
#login {
width:300px;
float:left;
border-radius:10px;
font-family:raleway;
margin-top:70px
input[type=text],input[type=password] {
width:99.5%;
padding:10px;
margin-top:8px;
padding-left:5px;
font-size:16px;
font-family:raleway
input[type=submit] {
width:100%;
background-color:#FFBC00;
color:#fff;
padding:10px;
font-size:20px;
cursor:pointer;
border-radius:5px;
margin-bottom:15px
}
#profile {
padding:50px;
font-size:20px;
background-color:#DCE6F7
#logout {
float:right;
padding:5px;
a {
text-decoration:none;
color:#6495ed
i {
color:#6495ed