ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Business and Employment»
  • Employment & Jobs»
  • Interviewing for a Job

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.

    Click to Rate This Article