আগামী ২৩ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Ajax with jquery

Ajax with jquery

This is actualy third part of beginning jquery
image001
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

DOWNLOAD CODE LIVE DEMO
$.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>
<html>
<head>
<meta charset="utf-8">
<title>Ajax search</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>

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

</div>
<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>
</body>
</html>

Save below as ajaxMethod.js in your js folder

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

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

Explanation:
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

<?php

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

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

Save below code as process.php

<?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");
$query->execute();
while ($finfo = $query->fetch(PDO::FETCH_OBJ)) {
echo '<div><h3>' . $finfo->title . '</h3>';
echo '<p>' . $finfo->description . '</p></div>';
}
?>

Explanation:
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

jquery_post

$.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.
LIKE
$.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) {
$('#result').html(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();

$.getJSON("process.php",{title:filmName},function(data){
var title="<ul>";
var description="";
for(var i=0;i<data.length;i++){
title+="<li>"+ data[i].title+"</li>";
title+="<p>"+data[i].description+"</p>";
}
title+="</ul>";
$('#result').html(title);

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

Process.php page

<?php
require '../connection.php';
$film_title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES);
$query = $dbh->prepare("SELECT * FROM film_text WHERE title LIKE '$film_title%' LIMIT 10");
$query->execute();
$data=$query->fetchAll(PDO::FETCH_ASSOC);
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

 

 

Hi,I am Tuhin Bepari from Bangladesh. I am a freelancer since 2011 working on odesk. I am not from Computer science background. But my passion about web programming make me a web developer. I am self motivated and always try to update with latest technology in my field.Now I am working on Yii Framework and Mongo DB.I have two other blog one is higher php and another is learn html5.

Leave a Reply

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