AJAX Inleiding

AJAX is een droom voor ontwikkelaars, omdat je kunt:

  • Vernieuw de pagina zonder de pagina te herladen
  • Vraag gegevens van de server op nadat de pagina is geladen
  • Ontvang gegevens van de server nadat de pagina is geladen
  • Verstuur gegevens naar de server in de achtergrond

AJAX Voorbeeld

Klik op de onderstaande knop om deze tekst met AJAX te veranderen:

Probeer het zelf

Uitleg van AJAX-voorbeeld

HTML-pagina

<!DOCTYPE html>
<html>
<body>
<div id="demo">
  <h2>Laat AJAX deze tekst veranderen</h2>
  <button type="button" onclick="loadDoc()">Verander tekst</button>
</div>
</body>
</html> 

Deze HTML-pagina bevat een <div> en een <button>.

<div> Voor het weergeven van informatie van de server.

<button> Roep de functie aan (wanneer deze wordt aangeklikt).

Deze functie vraagt gegevens van de webserver op en toont deze:

Function loadDoc()
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
} 

Wat is AJAX?

AJAX = Asynchronous JvaScript And XML.

AJAX is not a programming language.

AJAX is simply a combination of:

  • Browser's built-in XMLHttpRequest object (requesting data from the web server)
  • JavaScript and HTML DOM (display or use data)

Ajax is a misleading name. Ajax applications may use XML to transmit data, but transmitting data as plain text or JSON text is also common.

Ajax allows for asynchronous updates to the web page by exchanging data with the web server behind the scene. This means that parts of the web page can be updated without reloading the entire page.

How AJAX Works

AJAX
  1. An event occurs in the web page (page load, button click)
  2. The XMLHttpRequest object is created by JavaScript
  3. The XMLHttpRequest object sends a request to the web server
  4. The server processes the request
  5. The server sends the response back to the web page
  6. Response read by JavaScript
  7. Correct actions performed by JavaScript (such as updating the page)