CSCI 3342 Web Development
Fall 2024

Client-side page updates

AJAX POST

Sending data behind your back.
AJAX requests are just HTTP requests - the server doesn't even know the difference. We can make GET or POST requests and send data to the server in the URL or the POST body.
Unlike before, we won't be using an HTML form to generate the POST request with key-value encoding. We will be making an AJAX request using fetch, and sending along data from JavaScript encoded as JSON.
Navigate your browser to the static file http://localhost:8080/quotes.html
Client-side code for this part will be put in the linked file quotes.js.
On every user keystroke in the search box, use AJAX to update the list of quotes. An empty search box should return nothing (as opposed to everything).
(note: searching only for complete words would be more realistic, but SQL 'like' doesn't work that way and that is fine here.)
The video below gives an example of an AJAX POST. On the client:
  • Hook an event handler on the search box for every user keystroke
  • On every event, use fetch to retrieve /quote_search as JSON
  • When the data returns, clear the list of quotes and re-add the ones that were retrieved (just like part 2)
  • Change the AJAX GET query to a POST and send the search box contents in the POST body
  • (hint: This will break it, as there is no POST route to respond. Use the network panel to make sure your POST is sending the right data.)
  • (hint 2: Make sure you're sending a valid JSON object, not just a string.)
On the server:
  • Add the JSON middleware to your express server so it can receive JSON POST body data
  • Update /quote_search to be a POST route
  • Get the search string from the POST body, replacing fakestring

Video Example: AJAX POST (14:34)

Sending JSON data to a POST route via AJAX.