AJAX Examples Cheatsheet Code Example v1

AJAX calls Javascript fetch, Jquery ajax and XMLHttpRequest request examples

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.

Overview

#
  • An event occurs in a web page (the page is loaded, a button is clicked)
  • An XMLHttpRequest object is created by JavaScript
  • The XMLHttpRequest object sends a request to a web server
  • The server processes the request
  • The server sends a response back to the web page
  • The response is read by JavaScript
  • Proper action (like page update) is performed by JavaScript
  • XMLHttpRequest Object basic of
  • With JavaScript
  • Using Jquery

XMLHttpRequest

XMLHttpRequest to use to issue HTTP requests in order to exchange data between the web site and a server. It is a complex object that can be used asynchronously or synchronously. It is the bases of Javascript Fetch and Jquery ajax functions which reduce the complexity of the object, due to complexity . It can be used
  • Historical reasons: we need to support existing scripts with XMLHttpRequest.
  • We need to support old browsers, and don’t want polyfills (e.g. to keep scripts tiny).
  • We need something that fetch can’t do yet, e.g. to track upload progress.
Read More


						   

Javascript Fetch

Fetch is used to perform AJAX when working with JavaScript. Instead of writing cumbersome AJAX code or using libraries such as jQuery and Angular, the new JavaScript standard offers a more compact, modern, and flexible syntax. The fetch() method returns a promise true/falseand either json or text
Read More


						   

Jquery AJAX

whilst you can use the XMLHttpRequest request blocks , it is common to use Jquery .ajax routines to simply withmuch of an overhead.
Read More


						   

.ajax vs Fetch

Differents

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

Paramaters passing to php code

  • WIth .ajax use POST or get and on PHP side access the Super Glohal $_POST or $_GET
  • With fetch the super Glocam are not set so use $inputs = json_decode(file_get_contents('php://input'), true);

Advantages

  • .ajax