Skip to main content

Javascript Ajax Call



What is XMLHttpRequest(XHR)


The XMLHttpRequest object is used to exchange data with a server behind the scenes,
Its part of web pages,without reloading whole page.


It has been available ever since Internet Explorer 5.5 was released in July 2000.
XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side.
XHR request is exchange using XHR object.


The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability

XHR method :
1- abort(),
2-getAllResponseHeaders(),
3-getResponseHeader( headerName ),

Creating the Object :


var XmlHttp = new XMLHttpRequest();


XMLHttpRequest Properties


onreadystatechange
An event handler for an event that fires at every state change.


readyState
The readyState property defines the current state of the XMLHttpRequest object.


The following table provides a list of the possible values for the readyState property:


0-The request is not initialized.
1-The request has been set up.
2-The request has been sent.
3-The request is in process.
4-The request is completed.
readyState = 0 After you have created the XMLHttpRequest object, but before you have called the open() method.


readyState = 1 After you have called the open() method, but before you have called send().


readyState = 2 After you have called send().


readyState = 3 After the browser has established a communication with the server, but before the server has completed the response.


readyState = 4 After the request has been completed, and the response data has been completely received from the server.


responseText
Returns the response as a string.


responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties.


status
Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").


statusText
Returns the status as a string (e.g., "Not Found" or "OK").


AJAX Disadvantages
1-Open Source: View source is allowed and anyone can view the code source written for AJAX,
2-It can increase design and development time,
3-Security is less in AJAX application as all files are downloaded at client side.




Javascript Ajax Call:
Using javascript call ajax its very old method generally all people can’t use, because its very old method but i am explain that how its work.


Generally two method are use in ajax :
1-GET,
2-POST,


1-GET :
A "GET" request refers to sending information to the server using parameters tacked on to the current page's URL This can be done by directly adding


2-POST :
Using Ajax to send "POST" requests is very similar to that for "GET" requests, with a couple of differences. Traditionally "POST" is used when the information you're sending exceeds a certain size


Following is simple example of javascript ajax call :


Demo Link :
http://freeteachnology.hol.es/ajax_call/javascript/

Code Link :

1-javascriptHome.php,
2-javascriptSuccess.html,

1-javascriptHome.php :-
Simple GET method using call ajax using XMLHttpRequest object,


Following are simple exmaple of ajax:


Code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Javascript Ajax call</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
 <script   src="https://code.jquery.com/jquery-3.1.1.js"   integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="   crossorigin="anonymous"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<br>
<div class="container">
<div class="alert alert-info">
               <strong>Hi</strong> The XMLHttpRequest Object.
           </div>
 <div class="row">
   <div class="col-sm-6 col-md-6">
         <a id="ajaxButton" class="btn icon-btn btn-info" href="#"> Click here</a>
   </div>
 </div>
</div>
<br>
<!--Start:: if success ajax call then show message -->
 <div id="demo"></div>
<!--End:: if success ajax call then show message -->


<script type="text/javascript">
(function() {


 var httpRequest;
 document.getElementById("ajaxButton").onclick = function()
 {
   makeRequest('javascriptSuccess.html');
 };


 function makeRequest(url) {
   httpRequest = new XMLHttpRequest();
   if (!httpRequest) {
     alert('Giving up :( Cannot create an XMLHTTP instance');
     return false;
   }
     httpRequest.onreadystatechange = function() {
   if (httpRequest.status === 200) {
       document.getElementById("demo").innerHTML =httpRequest.responseText;
     }
   }
   //ajax post type:-
   httpRequest.open('GET', url);
   httpRequest.send();
 }


})();
</script>
</body>
</html>


Above example that on click call function makeRequest() and pass object url value, in this function call XMLHttpRequest() object if request is created then show alert cannot create XML instance.


If xml request is create onreadystatechange function call , if http request status 200 then ajax successfully call and success response show in demo id div and http request is GET.


2-javascriptSuccess.html


In  javascriptSuccess file contain only static message no more need explaination.


Code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Javascript Ajax call</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
 <script   src="https://code.jquery.com/jquery-3.1.1.js"   integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="   crossorigin="anonymous"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
   <div class="container">
<div class="row">
<div class="alert-group">
           <div class="alert alert-success alert-dismissable">
               <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
               <strong>Well done!</strong>The XMLHttpRequest Object : You successfully read this important alert message.
           </div>            
       </div>
</div>
</div>


</body>

</html>

Comments

Popular posts from this blog

using PDO database connection add,update,delete,edit operation

PDO advantage : 1-Object Oriented 2-Bind parameters in statements (security) 3-Allows for prepared statements and rollback functionality (consistency) 4-Throws catcheable exceptions for better error handling (quality) 5-Exception mode; no need to check error state after each API call. It's best to tell PDO how you'd like the data to be fetched. You have the following options: 1-PDO::FETCH_ASSOC: returns an array indexed by column name. 2-PDO::FETCH_BOTH: (default):returns an array indexed by both column name and number. 3-PDO::FETCH_BOUND:Assigns the values of your columns to the variables set with the ->bindColumn() method. 4-PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist. 5-PDO::FETCH_INTO:Updates an existing instance of the named class. 6-PDO::FETCH_LAZY: Combines. 7-PDO::FETCH_BOTH/PDO:FETCH_OBJ, creating the object variable names as t...

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links user want to share any information then use following code  and read step by step Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links if you want share profile on following social link : 1-Facebook 2-twitter.com 3-LinkedIn 4-google +, Code link : https://drive.google.com/open?id=1IzTZZh_0euDqFSHL_vPRiQePlNTw3h-q Demo link : http://freeteachnology.hol.es/socialshare/ To modify a page's thumbnail image, description, and additional metadata for these services, you can provide meta tags in the HTML code of the page.Implementing Open Graph Meta Tags You can implement meta tags in a number of ways. In content management systems might  be allow you to modify a page's meta tags , then use following code in meta section of your project code, <link href="bootstrap.min.css" rel="stylesheet"> <link href="bootstrap-tour.m...

GUID for globally unique identifier

How to create GUID in php 1-guid stands for globally unique identifier generally used to create random unique strings in php, create access token in php 2-Mostly use of GUID for generating access token, generate unique id, generating unique string in php. Using this article how to create guide in php you can create a random string for any use to keep unique 3-GUID consists of alphanumeric characters only and is grouped in five groups separated by hyphens as seen in this example: 3F2504E0-4F89-11D3-9A0C-0305E82C3301 Eg:- <?php /** * Generate Globally Unique Identifier (GUID) * E.g. 2EF40F5A-ADE8-5AE3-2491-85CA5CBD6EA7 * * @param boolean $include_braces Set to true if the final guid needs * to be wrapped in curly braces * @return string */ function generateGuid($include_braces = false) { if (function_exists('com_create_guid')) { if ($include_braces === true) { return com_create_guid(); } else { return substr(com_cr...