Ajax… it took a while for me to pronounce it A-Jax and not I-YAX( like the football team). :)
AJax makes it easier to send and retrieve from a server asynchronously, without having to refresh a web page. In my Tic-tac-toe(https://tic-tac-toe-rack.herokuapp.com) rack version, each mark on the board is a anchor link which makes a http request which would looks like this for board mark on the top left.
This request sends the move, an empty board and a human vs human game type as part of the http parameter string.
Once the button is click it directs to the specified URL, causing the page to refresh.
This works but it isn’t as nice of a user experience. That’s where Ajax comes in.
Lets go more low level..
Here are overview steps of AJAX Operation A client event occurs.
- An XMLHttpRequest object is created.
- The XMLHttpRequest object is configured.
- The XMLHttpRequest object makes an asynchronous request to the Webserver.
- The Webserver returns the result containing XML document.
- The XMLHttpRequest object calls the callback() function and processes the result.
- The HTML DOM is updated.
A Basic Example with Rack
Here below is my Rack back end which takes a request and responds with a converted arabic string.
To convert the arabic parameters, I’ve created a simple converter that takes the arabic parameter from the query string and returns the roman value. Careful to note that the Rack::Request object is a convenient interface to the rack environment, which makes it easier to access the query string as key value pairs.
Next we use the request converter to convert into something that the back end can understand, calculate and return. This is being done through the rudimentary “arabic” method, which is reading the parameters hash given through the constructor.
In the client side, we have a script that adds an event handler to a button, which makes a request by the value held in the input box.
That’s it for making a Ajax request with a callback.