Chapter 2. Using Ajax and JSON

This chapter is about bringing external data to our HTML web pages. In Chapter 1, we used only hardcoded data because our goal was to show how to lay out the web page and how to change that layout in response to certain events (for example, the user clicking a menu button). Now we’ll make sure that our single-page application, Save The Child, can request data from external sources and send data, too. This comes down to two questions:

  • How does an HTML web page exchange data with web servers?
  • What format do we use to present the application data?

Even though there could be different answers to these questions, we’ll be using Ajax techniques as an answer to the first question and JavaScript Object Notation (JSON) data format as an answer to the second one. We’ll start this chapter by explaining why Ajax and JSON are appropriate choices for the Save The Child web application and many others.

Understanding Ajax

In the early days of the Internet, every new page, whether it was hosted on the same or separate website, required a new request and response to the web server. This, in turn, would re-render the entire contents of the new page. If a user points her web browser to one URL and then changes it to another, the new request will be sent to the new URL, and the new page will arrive and will be rendered by the browser. The URL might have been changed not because the user decided to go to visit a different website, but simply because the user selected a menu ...

Get Enterprise Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.