Ajax with jquery

Ajax with jquery

Ajax with jquery

This is actualy third part of beginning jquery
What is AJAX?
Ajax (Asynchronous JavaScript and XML) is a method of building interactive Web applications that process user requests immediately.
Ajax allows content on Web pages to update immediately when a user performs an action, unlike an HTTP request, where users must wait for a whole new page to load. Ajax will load only a portion of web page and rest of them remain unaffected. Google map is one well-known application that uses Ajax

$.ajax() method in jquery

$.ajax is similar to javascript XMLHttpRequest object.$.ajax is more simple and easy to use compare to XMLHttpRequest.

$.ajax method have couple of property which are

url: Where you want to send request. This would be within your domain.
type: Request type like POST,GET

dataType: what type of data you want in response of request like html,json,xml

data: Data you want to sent.

success: If you get response successfully then what you do with that response data
complete: add jquery or javascript code to the response code. Because,outside jquery or javascript code does not work with ajax response content.
Error: If an error occur then this will run. Usually, it takes anonymous function and its first parameter is object, second parameter is status, third one is text response.
save below code as index.php

<!doctype html>
<meta charset="utf-8">
<title>Ajax search</title>
<link rel="stylesheet" type="text/css" href="css/style.css">

<input type="text" name="film_title" id="title" placeholder="type film title"><span id="total"></span>
<div id="result">

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/ajaxMethod.js"></script>

Save below as ajaxMethod.js in your js folder

$(document).ready(function(e) {
$('#title').on('keyup', function() {
var filmName = $(this).val();
url: 'process.php',
type: 'POST',
dataType: "html",
data: {title: filmName},
success: function(data) {

complete: function() {
var count = 0;
$('h3').each(function() {
$('#total').text(count + ' result found');
});//end of ajax method
});//end of on key up method
});//end of ready method

Here we use keyup event.Inside this event, we grab the value of input field. After that, We initialize jquery ajax method and pass a object inside ajax method parameter. This object have some specified key which already discussed above. In url we give a page name where request will be sent. Then which type of request we want to sent GET or POST that defined in type property. What type of data we want as a response from requested url that defined in dataType. what data will be sent to request url (as $_POST or $_GET) that defined in data property. Here i just sent one variable which is title.

Remember, key is variable $_POST or $_GET array index like $_POST[‘title’] and second part is its value.
Multiple value can be sent by giving comma after one pair. A whole array can also be sent only giving array name on data property, for that no need to key or value. Array key will be key and keys value will be value of that key in process page’s $_POST or $_GET super global.
Success function receive data from the requested url if request is succeed. Here anonymous function parameter is actually response data.
In complete property it counts how many result came as response of request.

Create a database as entertainment and import film_text.sql file there. That will create a film_text table.
Or you can work with your own database. For that change database name and table along with sql query.

Save below as connection.php


$dsn = 'mysql:dbname=entertainment;host=';
$user = 'root';
$password = '';

try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();

Save below code as process.php

//grab data from index.php page
$film_title = htmlspecialchars($_POST['title'], ENT_QUOTES);
$query = $dbh->prepare("SELECT * FROM film_text WHERE title LIKE '$film_title%' LIMIT 10");
while ($finfo = $query->fetch(PDO::FETCH_OBJ)) {
echo '<div><h3>' . $finfo->title . '</h3>';
echo '<p>' . $finfo->description . '</p></div>';

Beginning part is database connection via PDO(php database object) or others can also be used such as mysqli class, mysqli procedural style. That depend up to developer which type of connection they prefer.
within while loop i create information box wrapped with div. If 10 result found then 10 div will created and sent to index.php in success property anonymous function.

Jquery Post method


$.post(),$get(),$.getJSON() are child method of $.ajax(). All of these method call $.ajax method internally to work.These three are the short cut syntax of $.ajax method.
$.post() and $.get() syntax are same.
First parameter: URL
Second Parameter: Data which will be sent to target url.You can give an single array or pass an object like {key:value,key:value}
Third parameter: success function.What you do with the response data if request succeeded.
$.post(‘post_response.php’, info, function(responseData) { alert(responseData);
Now we are going to find movie title using previous index.php and processs.php and connection.php page
Just change the js file ajaxMethod.js to ajaxPost.js
LIKE below

<script type="text/javascript" src="js/ajaxPost.js"></script>
Save the following code as ajaxPost.js
$(document).ready(function(e) {
$('#title').on('keyup', function() {
var filmName = $(this).val();
$.post('process.php',{title: filmName},function(data) {
);//end of ajax method
});//end of on key up method
});//end of ready method

Notice how easy and simple this $.post method is compare to $.ajax method.But here we lost some control like complete, error, dataType and so on. Now use $.post or $.ajax method depends on your application need.
Jquery get JSON data
Please read An introduction to json from this webstite if you have no knowledge about json
An introduction to JSON
There are two way to get json data as a response, first one is set dataType to json on $.ajax method and process responded json data on success callback function. On the other hand, you can use $.getJSON short syntax for handling json data.
Why json is important?
In $.ajax() and $.post() we have no control in client side language(like javascript) how to organize and distribute data among the document. We just insert response data as html or text to another div. But we may need to show film title to one div and description and other information to another div or anywhere we want using jquery or javscript. Then have to use $.getJSON.
$.getJSON() have same syntax as $.post(). Just name changed.
Index.php page are same as ajax method page( very first page of this article).
Save this jquery code as json.js in your js folder

$(document).ready(function(e) {
$('#title').on('keyup', function() {
var filmName = $(this).val();

var title="<ul>";
var description="";
for(var i=0;i<data.length;i++){
title+="<li>"+ data[i].title+"</li>";

});//end of on key up method
});//end of ready method

Process.php page

require '../connection.php';
$film_title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES);
$query = $dbh->prepare("SELECT * FROM film_text WHERE title LIKE '$film_title%' LIMIT 10");
echo json_encode($data);
JSON data Structure of this response
This is sample response data to give an overview how to use this structure json data in success callback function to arrange or view them in web page.
"film_id": " film id",
"title": "film title",
"description": "descritpion"
"film_id": " film id",
"title": "another film title",
"description": " another descritpion"

For more information about json data structure check This post



One comment to “Ajax with jquery”

Leave a Reply

Your email address will not be published. Required fields are marked *