Interacts with the user, but does not talk to the network.
JavaScript cannot add anything to the page that isn't local.
When data is needed from the server, a new page must be loaded
by clicking a link or a page load commanded from JavaScript.
Enter the XMLHttpRequest object.
Originally invented by MS for Internet Explorer.
It allows JavaScript to create and send an HTTP request, and
collect the result.
So JavaScript can retreive data from a server and add it to the current
page without the overhead of a full round-trip, HTML parse and display.
Allows pages to be much more interactive.
XMLHttpRequest remains part of JavaScript, but its always been
clunky to use.
This technique goes by the name AJAX, for
“Asynchronous JavaScript and XML,” even though XML is rarely
used anymore.
JavaScript Object Notation (JSON)
AJAX using XMLHttpRequest imagines the JavaScript client exchanging
data in XML format with the server. Today, more common to use JSON.
A much simpler text format use to represent a structured data value.
Could be a single value, but almost always something larger.
Usually an array or simple object, and each value may also be
an array or simple object.
JSON expressions are often used to transfer information between
a JavaScript client and a server.
While a JSON string is legal JavaScript constant,
it's usually not safe to simply
let the JavaScript interpreter execute some string that came from
who-knows-where.
Examples:
{"remaining":18, "first":["snail","wombat","emu"],
"last":["game show host","lawyer"]}
Keys are limited to quoted strings, and values must be objects or arrays,
or single strings, numbers, booleans or null.
JavaScript has since introduced the newer fetch method to
replace the XMLHttpRequest object.
The send method uses a newer feature called a “promise”.
A promise is an improved way of managing callbacks. It
essentially represents some task that is in queue (pending),
competed (fulfilled) or failed (rejected). (Failure
means it threw an exception.)
The then method runs a callback with the result
if and when the task succeeds.
The catch method (not statement) runs a callback if and
when the task fails.
The then and catch methods also return promises, so the calls may be
chained.
The script
does not generate or send HTML and is not intended to be visited
in a browser.
Depending on the query part of the URL,
the script generates either plain text or JSON.
The PHP accepts messages from the JavaScript which are sent as request
data, and stores them in a file. It responds with just a plain text
OK or error message.
It accepts polls and responds with an error or a JSON document
reporting any requested messages. (This could be zero messages.)
Interaction:
The client sends requests to the server.
Simple responses are plain text, more complicated ones are JSON.