ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

AJAX Interview Questions and Answers with Examples And Notes

Updated on May 22, 2014

AJAX got its name from “Asynchronous JavaScript and XML.” It is not a single technology or language, but a group of technologies. It is a way to exchange data with a server so that a web page can update parts of itself without reloading the whole page.

AJAX works as follows: A browser, when an event occurs (for example, a keystroke or mouse click), creates a request object and sends a client-side script to a server, and the server sends a server-side script back. The browser processes the returned script using JavaScript, and updates the page without reloading it.

Source

What are the Differences Between AJAX and JavaScript?

JavaScript manages and controls a Web page after being downloaded. When JavaScript posts a request, it waits for a response and then refreshes the page.

AJAX sends a request to the server and does not wait for the response. It performs other operations on the page during that time. AJAX does not require the whole page to refresh and be downloaded again. Thus AJAX reduces the load on the server.

What Are Some Examples of Applications that Use AJAX?

  • Google Maps
  • Gmail
  • YouTube
  • Facebook Tabs

Is AJAX a Technology Platform or an Architectural Style?

It’s both. Ajax is a set of technologies being used together in a particular way.

What Technologies are Used in AJAX?

AJAX uses the following four technologies:

  • JavaScript
  • XHR (XMLHttpRequest)
  • Document Object Model (DOM)
  • Extensible HTML (XHTML) and Cascading Style Sheets (CSS)

What is an Event Handler?

An event handler will run a function when something happens, for example, a keystroke or movement of a mouse.

What Is the Format of an AJAX Request?

An AJAX request can be in any format:

  • Text File
  • HTML
  • JSON object

What Is XHR and What Is it Used for?

XHR stands for XMLHttpRequest. XHR objects, or XMLHttpRequest objects, are used in the following ways:

  • An XHR object is used by JavaScript to transfer XML and other text data between client and server.
  • The XHR object allows a client-side script to perform an HTTP request.
  • AJAX applications use the XHR object so that the browser can communicate with the server without requiring a post-back or refresh of the entire page.

Note: Old versions of Internet Explorer (6 and earlier) used MSXML ActiveX instead of XHR to provide this functionality.

What Is JSON?

JSON stands for JavaScript Object Notation. It is a safe and reliable data interchange format in JavaScript, which is easy to understand, not only for users but also for machines.

When Should We Avoid Using AJAX?

  • When a browser does not support JavaScript.
  • When we want to create a secure application.
  • When we want our webpages to be visible to major search engines like Google, Yahoo, and Bing.

Why is AJAX a Problem for Visibility in Search Engines?

A web crawler does not execute JavaScript code, and AJAX is JavaScript.

Does an AJAX Request Work on Different Domains?

No. An AJAX request works only within the same domain.

Is an AJAX Request Synchronous or Asynchronous?

AJAX requests are asynchronous by nature, which means that they should run in the background independently of other events.

Is AJAX Code Cross-Browser Compatible?

Not totally. Most browsers offer a native XMLHttpRequest JavaScript object, while old versions of Internet Explorer require you to get it as an ActiveX object.

What Are the Reasons for the Types of Errors Shown Below?

  1. XMLHttpRequest cannot load file:///C:/Tutorials/jQuery/practices/ajax/dataFile.txt. Cross origin requests are only supported for HTTP.
  2. Uncaught NetworkError: A network error occurred.

An AJAX request cannot be executed without the server. To get a reply, we need to execute the AJAX request into the server. So, if the requested object is missing in the server, the above error could result.

"XMLHttpRequest Cannot Load," "Uncaught Network Error"
"XMLHttpRequest Cannot Load," "Uncaught Network Error"

What is the Meaning of 404 or 500 Status in AJAX?

It means that the AJAX call to the server is unsuccessful.

What is the Meaning of 200 Status in AJAX?

It means the AJAX call to the server is successful (see below).

"Status: 200"
"Status: 200"

What is the Meaning of "False" in the Following Line of Code?

request.open('GET', 'MyData.txt', false)

It means the request is a synchronous request.

How Do You Retrieve the State of the Requested Process?

By using the property “readyState” of XMLHttpRequest object (XHR Object), which uses numeric values to represent the state.

What Does It Mean if ReadyState has the Value 0?

A readyState of 0 means the request hasn't been sent yet.

What Does It Mean if ReadyState has the Value 4?

A readyState of 4 means the request has seen sent and received.

How Do You Call Server-Side Code From JavaScript?

To call the server-side code from JavaScript, we can use the techniques “page methods” and “Web services.”

How Do You Create an AJAX object? What is Its Syntax?

var myAJAZXOject = new AjaxObject("page_url");

Now, Some Examples

Source

Six Examples of AJAX Code, With Notes

In the following section, you will find some examples of AJAX code.

AJAX Example 1: A Synchronous XHR Request

The following is a simple and easy XHR example. It consists of three files:

  • index.html file:: the main HTML file which includes the AJAX script
  • MyScript.js file: all AJAX codes are there
  • MyData.txt file: normal data file

What this example does is that when the index.html page is requested, it prints the contents of MyData.txt file into the browser. Below is the full code and output for this example.

index.html file

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Learning JavaScript AJAX [PlusMinus]</title>
	</head>
	<body>
		<script src="MyScript.js"></script>
	</body>
</html>

MyScript.js file

for (var i = 0; i < 3; i++) {
	var request = new XMLHttpRequest();
	request.open('GET', 'MyData.txt', false);
	request.send();
	if (request.status === 200) {
		console.log(request);
		document.writeln(request.responseText);
	}
}

MyData.txt file

Hello PlusMinus!
Example 1:  Synchronous XHR request
Example 1: Synchronous XHR request

Backward compatibility with AJAX (Example 1)

var request;

if (window.XMLHttpRequest) {
	request = new XMLHttpRequest();
} else {
	request = new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', 'MyData.txt');
request.onreadystatechange = function() {
	if ((request.readyState === 4) && (request.status === 200)) {
		console.log(request);
		document.writeln(request.responseText);
	}
}

request.send();

AJAX Example 2: Updating IDs

Using AJAX, we can update IDs. In this example we define an ID in the index.html file, name the ID “MyID,” and change the value of the ID with the value of responseText.

index.html file

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Learning JavaScript AJAX [PlusMinus]</title>
	</head>
	
	<script src="MyScript.js"></script>

	<body>

		<div id="myID">

		</div>

	</body>
</html>

MyScript.js file

var request = new XMLHttpRequest();
request.open('GET', 'MyData.txt');

request.onreadystatechange = function() {

	var modify = document.getElementById('myID');
	modify.innerHTML = request.responseText;

}

request.send();
Example 2:  Updating IDs
Example 2: Updating IDs

AJAX Example 3: GetElementsByTagName, Displaying a Response Text In a Spot In A List

We have an ordered list with three items. Using AJAX, display the value of responseText as the second item in the list.

index.html file

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Learning JavaScript AJAX [PlusMinus]</title>
	</head>

	<script src="MyScript.js"></script>

	<body>

		<ol>
			<li></li>
			<li></li>
			<li></li>
		</ol>

	</body>
</html>

MyScript.js file

var request = new XMLHttpRequest();
request.open('GET', 'MyData.txt');

request.onreadystatechange = function() {

	var modify = document.getElementsByTagName('li');
	modify[1].innerHTML = request.responseText;

}

request.send();
Example 3:  Displaying ResponseText in a List
Example 3: Displaying ResponseText in a List

AJAX Example 4: GetElementsByTagName, Displaying a Response Text in a List Inside an Ordered Group

Here we have a group of three ordered lists. Using AJAX, we display the value of responseText in the second spot in the second list.

index.html file

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Learning JavaScript AJAX [PlusMinus]</title>
	</head>

	<script src="MyScript.js"></script>

	<body>

		<ol>
			<li></li>
			<li></li>
			<li></li>
		</ol>
		<ol>
			<li></li>
			<li></li>
			<li></li>
		</ol>
		<ol>
			<li></li>
			<li></li>
			<li></li>
		</ol>

	</body>
</html>

MyScript.js file

var request = new XMLHttpRequest();
request.open('GET', 'MyData.txt');

request.onreadystatechange = function() {

	var modify = document.getElementsByTagName('ol')[1].getElementsByTagName('li');
	modify[1].innerHTML = request.responseText;

}

request.send();
Example 4:  Displaying ResponseText in a list inside a group
Example 4: Displaying ResponseText in a list inside a group

AJAX Example 5: Using AJAX to Read JSON data

In this example, we have a JSON data file which contains a list of names American states. We will list all the state names using AJAX, and read JSON data to output the state names into the browser.

Note: JSON parse is not available for all browsers. Solution to this problem: use jQuery.

index.html file

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>JavaScript AJAX Learning </title>
	</head>
	<script src="MyScript.js"></script>

	<body>

		<div id="usStates">
			
		</div>

	</body>
</html>

MyScript.js file

var request;
if (window.XMLHttpRequest) {
	request = new XMLHttpRequest();
} else {
	request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'USA_States.json');
request.onreadystatechange = function() {
	if ((request.readyState === 4) && (request.status === 200)) {
		var listOfStates = JSON.parse(request.responseText);
		console.log(listOfStates);
		var output = '<ul>';
		for (var key in listOfStates) {
			output += '<li>' + listOfStates[key].name + '</li>';
		}
		output += '</ul>';
		document.getElementById('usStates').innerHTML = output;
	}
}
request.send();

USA_States.json file

[
    { "name": "MARYLAND", "abbreviation": "MD"},
    { "name": "NEW JERSEY", "abbreviation": "NJ"},
    { "name": "NEW YORK", "abbreviation": "NY"},
    { "name": "VIRGINIA", "abbreviation": "VA"},
    { "name": "WASHINGTON", "abbreviation": "WA"}
    
]
Example 5 no. 1
Example 5 no. 1
Example 5, no 2
Example 5, no 2

We can also use the ID to define the mouse-click functionality on that ID to display the above scenario. If we would like to do that, we need to make the following change to our codes:

index.html file

<!DOCTYPE html>
<html lang="en">
	<body>
		<button id="buttonID">
			View the states
		</button>
		<div id="usStates"></div>
		<script src="MyScript.js"></script>
	</body>
</html>

MyScript.js file

var mybutton = document.getElementById('buttonID');
mybutton.onclick = function() {

	var request;
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else {
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}
	request.open('GET', 'USA_States.json');
	request.onreadystatechange = function() {
		if ((request.readyState === 4) && (request.status === 200)) {
			var listOfStates = JSON.parse(request.responseText);
			console.log(listOfStates);
			var output = '<ul>';
			for (var key in listOfStates) {
				output += '<li>' + listOfStates[key].name + '</li>';
			}
			output += '</ul>';
			document.getElementById('usStates').innerHTML = output;
		}
	}
	request.send();

}

AJAX Example 6: jQuery, Reading Data From a JSON File

We will use .getJSON to read the JSON file and display it in this example. To complete this example we need the jQuery javaScript file, which can be downloaded from the jQuery official website.

Example 6 no. 1
Example 6 no. 1

index.html file

<!DOCTYPE html>
<html lang="en">
	<body>
		<div id="usStatesID">
			<h1>States</h1>
		</div>

		<script src="jquery.js"></script>
		<script src="MyScript.js"></script>
	</body>
</html>

MyScript.js file

$.getJSON('USA_States.json', function(data) {
	console.log(data);
	var output = '<ol>';
	$.each(data, function(key, value) {
		output += '<li>' + value.name + '</li>';
	});
	output += '</ol>';
	alert(output);
	$('#usStatesID').html(output);
	// $('#usStatesID').append(output);
	// $('#usStatesID').prepend(output);
});

USA_States.json file

[
    { "name": "MARYLAND", "abbreviation": "MD"},
    { "name": "NEW JERSEY", "abbreviation": "NJ"},
    { "name": "NEW YORK", "abbreviation": "NY"},
    { "name": "VIRGINIA", "abbreviation": "VA"},
    { "name": "WASHINGTON", "abbreviation": "WA"}
    
]
Example 6 no. 2
Example 6 no. 2

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)