📖 JavaScript AJAX
AJAX (Asynchronous JavaScript and XML) is a method of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
There is a really good video tutorial on JSON and AJAX on YouTube.
AJAX combines several Web technologies.
- XHTML for structure
- CSS for presentation
- Document Object Model (DOM) for displaying and manipulating pages
- XMLHttpRequest browser object for transferring data between the client and server
- XML as the data format
- JavaScript to dynamically display and interact with the other technologies
The key to AJAX is the XMLHttpRequest object which allows us to detach the browser application from the server by transferring the data in the background so the browser application doesn't have to wait for the server each time the user wants to access the information.
Some examples of pages that use AJAX include Google maps, YouTube, and Facebook tabs.
How AJAX Works
The XMLHttpRequest Object
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
The process for completing the AJAX process using JavaScript is.
- Create an instance of the XMLHttpRequest object.
- Use the xhttp.open() method to specify the method of sending the data and the target.
- Create a function to handle the results.
- Send the request.
- Receive the response.
Example
// create a new XML HTTP request
const xhttp = new XMLHttpRequest();
// use the open method to connect to the data target
xhttp.open("GET", "simple-data.json", true);
// create a function to handle the data
xhttp.onload = function () {
// receive the data
data = this.responseText;
// parse the data
const obj = JSON.parse(data);
// prepare the output HTML
document.querySelector('#name').innerText = obj.name;
document.querySelector('#title').innerText = obj.superPower;
}
// send the request
xhttp.send();
Simple JSON Data
{
"name": "Stephen Herd",
"title": "Professor",
"superPower": "Grading Homework"
}
AJAX Using jQuery
jQuery simplifies the process of using AJAX with several functions.
load()
Loads an html file into an element on the page.
Format
$('selector').load('filename selector2');
/* where selector is the selector for the element on the page where the content will be loaded */
/* filename is a relative path to the file on the server to be loaded */
/* selector2 is optional and is used to only load part of a page as identified by the selector */
get() and post()
Sends and retrieves information from a web server that is not in html format. Which one to use may be driven by the server program but generally get() is used for small amounts of data and post() for larger amounts of data or sensitive information.
Format
$.get('url','data','callback');
/* OR */
$.post('url','data','callback');
/* where url is the path to the server side script */
/* data is the data being passed to the script */
/* callback is the function that will process the information returned from the server */
The data being sent to the server must be in a format that is understood by the server script. This can take one of 2 forms.
- querystring
- series of name=value pairs beginning after the ? and connected by the &
- must be encoded for special characters using built-in function encodeURIComponent()
Format
www.domain.com?name1=value1&name2=value2
- object literal
- better for larger amounts of data and special characters
- may contain 1 or many sets of "name":"value" pairs
Format
{"name1":"value1", "name2":"value2",... "nameX":"valueX"}
Error Handling
- add .error(errorHandler) function at the end of the .get() or .post() function
- errorHandler refers to a function that takes action based on the error.
JSON
JavaScript Object Notation is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. Common format for data sent from a server.
JSON data looks like a JavaScript object literal.
/* JSON Data Example */
{"name":"value", "name":"value",... "name":"value"}
/* JSON Data Arrays */
{"customers":[
{ "firstName":"Joe", "lastName":"Smith", "company":"Acme" },
{ "firstName":"Roy", "lastName":"Rogers", "company":"Rope-A-Dope" },
{ "firstName":"Peter", "lastName":"Piper", "company":"Pickles" }
]}
To retrieve JSON data from the server.
/* Access the server */
$.getJSON('url','data','callback');
To access the value of a object literal called name.
data.name
To process multiple values with the same name use
$.each(JSON, function('name','value') {
access values...
};
XML
- Another common format for data sent from a server.
- Looks like html tags but tags are user defined.
- Must know from server what tags are expected.
- To access an xml field use
$(data).find('name').text();
- Commonly used for rss feeds from a blog or news source.
Format
/* XML */
<customers>
<customer>
<firstName>Joe</firstName>
<lastName>Smith</lastName>
<company>Acme</company>
</customer>
<customer>
<firstName>Roy</firstName>
<lastName>Rogers</lastName>
<company>Rope-A-Dope</company>
</customer>
<customer>
<firstName>Peter</firstName>
<lastName>Piper</lastName>
<company>Pickles</company>
</customer>
</customers>
RSS Feed Example
Using jQuery to Display an RSS Feed
Note: This information is not in the book.
RSS feeds are information aggregators. Many sites allow you to access their site content and 'feed' it to your site or app. There is a good beginner article on Google that helps explain how feeds work.
- RSS feeds all have the same layout.
- Each individual entry is enclosed in <item></item> tags.
- Inside each item is a <title>, <link>, <description>, and <pubDate>.
Unfortunately, JavaScript can only access local files, so you have to use a php proxy program to download the rss feed. I have provided a php proxy program that you can use for this. It is attached to the lesson below. Just save it in your web folder and use it in the $.get statement specifying the url of the rss feed website: $.get('proxy.php?url=rssFeedUrl',function(data).
Save the code below as PHP file named proxy.php
. This file will access the RSS Feed specified in the $_GET['url']
as an XML file and return to the calling JavaScript file.
<?php
header('Content-type: application/xml');
$handle = fopen($_GET['url'], "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
Here is the sample JavaScript for adding an RSS feed on your page. Add this to the head section of your RSS Feed page. Notice how JavaScript sends the URL of the RSS Feed to the proxy.php
script in a querystring (?url=https:css-tricks.com/feed/?format=xml
) using $.get
. PHP then returns the contents of the RSS Feed in an XML file for JavaScript to process.
/* Create a JavaScript file named rss-feed.js */
$(document).ready(function () {
$.get('proxy.php?url=https://css-tricks.com/feed/?format=xml', function (data) {
// check to see the type of data loaded
console.log(data);
// grab the feed title
var title = $(data).find('channel > title');
$("#title").html(title);
// grab the feed description
var description = $(data).find('channel > description');
$("#description").html(description);
// grab the feed posts
var itemNum = 0;
$(data).find('item').each(function () {
$item = $(this);
itemNum++;
// grab the post title
var title = $item.find('title').text();
// grab the post URL
var link = $item.find('link').text();
// next, the description
var description = $item.find('description').text();
// don't forget the published date
var pubDate = $item.find('pubDate').text();
pubDate = pubDate.slice(0, pubDate.length - 15);
// grab the related categories and assemble them
$cat = "<p style='font-size: smaller;'>Categories: "
$item.find('category').each(function () {
$cat += (" | " + $(this).text() + " ");
});
$cat += "</p>";
// format the post
var post = "<fieldset>" +
"<legend> Article " + itemNum + " </legend>" +
"<h4><a href='" + link + "'>" + title + "</a></h4>" +
"<p>" + pubDate + "</p>" +
description +
$cat +
"</fieldset>";
// limit the output to 5 posts
if (itemNum <= 5) {
// add the post to the feed
$('#feed').append(post);
}
}); // end find
}); // end get
}); // end ready
Don't forget to add the necessary html elements to display the parts of the RSS Feed. You can modify the styles to suit your application. You can see it in action on the server at link 2learnweb.
<!-- Add this to the head section of your html file -->
<script src="rss-feed.js"></script>
<!-- Add this to the body of the HTML -->
<div id="feed">
<h2 id="title"></h2>
<h3 id="description"></h3>
</div>
Finding RSS Feeds
There are several organizations that provide RSS feeds. Google has FeedBurner that is mainly designed to work with Google apps but you can find a few feeds if you dig around. Google is changing the FeedBurner service so feeds may not work with FeedBurner in the future.
To find independent feeds to add to your site, you have to search the individual organization to see if they offer a feed aggregator. Find a website that offers a RSS feed and click the feed to load it in your browser. Right-click the page to select View [Page] Source and you should find the link to the feed source. Look for a link with the ?format=xml or an .xml file extension. These are the server resources that provide the feed. You can try them out by pasting the link URL into your rss-feed.js file.
The US Census Bureau offers a few feeds that we can use for practicing our AJAX assignment. Visit https://www.census.gov/about/contact-us/feeds.html to see a list of available feeds. Just click on the feed link to make sure it is still producing content, then add the URL of the feed to your rss-feed.js file.
Another way to find popular feeds is to visit the rss.com page. This site promotes the use of RSS feeds and is a good source of examples.
To find a feed on rss.com...
- Open https://rss.com/blog/popular-rss-feeds/
- Find a feed of interest to you and click the RSS Feed button.
- Save the file to your computer.
- Right-click the file and select Open with > VS Code.
- You should see the XML feed data that shows the structure of the feed and its source file link.
- Find the feed link... something that says - atom:link type="application/rss+xml" - in the link.
IE:<atom:link href="https://rss.art19.com/apology-line" rel="self" type="application/rss+xml"/>
- Copy the feed link URL (href value) to the feed IE:
https://rss.art19.com/apology-line
- Paste the feed link URL into your rss-feed.js file.
- Refresh your feed page to see if you get the feed.