What is AJAX?
How pages request data in the background, what requests and responses are, and setting up a local server to practise.
Pages that update themselves
Without AJAX, every time you send a form or click a link, the browser throws the page away and loads a new one. With AJAX, JavaScript quietly asks the server for data and changes only the part of the page that needs changing.
You already use it every day: search suggestions, "like" buttons, chat messages and infinite scrolling all work this way.
| Without AJAX | With AJAX |
|---|---|
| The whole page reloads | Only part of the page changes |
| The screen flashes white | Smooth, app-like feel |
| Scroll position and typed text are lost | Everything else stays as it is |
| The server sends a whole HTML page | The server usually sends small JSON data |
Request and response
- JavaScript sends a request to a URL, for example
search.php?q=html. - The server (PHP) does its work, such as a database query.
- The server sends back a response, usually JSON data.
- JavaScript reads the response and updates the page.
Set up your practice folder
AJAX needs a real web server, because browsers block requests from pages opened straight from your disk.
- Install XAMPP and start Apache (and MySQL for the later lessons).
- Create the folder
htdocs/learn-ajax. - Open your pages at
http://localhost/learn-ajax/..., never by double-clicking.
Check your understanding
Quick check
What does AJAX let a page do?
Quick check
What format do most AJAX responses use today?
Quick check
Why open AJAX pages through http://localhost/...?