Convert to AJAX Submission, API Response

Purpose: You will transform the add professional form from Exercise 4.3 so the back end makes simple API responses and the front end uses AJAX to communicate with the server instead of refreshing the page on each submit.

Required Reading

It has become common practice in web programming to push as much HTML- and view-related functionality to the client side as possible, leaving the server as mostly an API engine that receives endpoint URLs and responds in JSON or XML rather than rendering a whole HTML template in response.

UI (User Interface) is for human-to-software interactions, and API (Application Programming Interface) is for software-to-software interactions. Up until now, all of your Flask route functions, including your POST routes, have ended with a call to render_template, which responds to the client in HTML (a UI-focused language). APIs do not typically respond in HTML, but in software-friendly formats like JSON, XML, or structured text. While a typical UI emphasizes human factors like intuitiveness and visual appeal, a typical API emphasizes machine factors like efficiency and data structure.

Project Part 4.5 starts the journey of separating UI and API features. Project Part 5 will complete the separation. This exercise gives you an important start to Project Part 4.5, changing the UI of the add professionals form to submit the form with Javascript (using AJAX) without refreshing the page.

Step 1. Convert Server Responses from UI to API

Start with the demo form to insert a professional from Exercise 4.3. In app.py, in the "/professionals_add" POST route, convert the following:

From To
message = "" message = "ok"
message="Please fill out all fields" message="err_missing"
message="Please provide a valid image file" message="err_filetype"
return render_template( ... ) return message

Simple text message responses like this are the simplest form of API. It is more common to use JSON responses, but the hope is that doing it this way will help you grasp the fundamentals of API. If you test at this point (please do), you will find that submitting the form brings you to a blank page with only the API message. This is obviously not an ideal state to stay in, because we are mixing UI and API, so we should fix it in the next step.

Step 2. Convert Form Submission to AJAX

Since the point of an API is for the machine to see it, not the user, convert your form to get the API response without displaying it on the page, as follows: Creating the following Javascript function in a new file, static/index.js.

index.js

Include index.js in templates/common/layout.html using <script src="static/index.js"><script>.

Now, in professionals_add.html, override the form submission simply by adding onsubmit="add_professional(event)" to the <form> tag. The onsubmit attribute is an event handler that takes any Javascript for a value. It runs just before the default form submission behavior happens. Javascript passes an object named "event" to it. Study the following features of the function above:

Please take a moment to use console mode to run the FormData collection and pass it to fetch in the headers object until you are comfortable with what these lines do on their own.

Also, note the form no longer strictly needs an "action" attribute. You can either keep it or get rid of it, but if you keep it, you may want to make your AJAX function make use of its value. Alternatively, if you set action="javascript:void(0)" it acts the same as running event.preventDefault().

Step 3. Prevent Unwanted Duplicate Submissions

AJAX requests can take time. While an AJAX submission is pending, the user may not know what is going on and may click on the button multiple times, causing duplicate submissions.

An easy way to prevent this is: In the add_professional() function, underneath the line var form = event.target;, add form.disabled = true; to disable the form, then, on the line after the await is done, add form.disabled = false;.

Step 4. Refresh the List Without Refreshing the Page

The most important feature of transitioning from UI to API in web applications is to avoid needless page refreshes. It is better to refresh part of the page than the whole page. For now, you will do this by refreshing the professionals list without refreshing the page.

First, in professionals_list.html, wrap a div around the {% include %} directive that includes "professionals_list.html" so that the content of this div can be easily replaced.

Second, in app.py, create a route (perhaps call it "/professionals_refresh") which simply returns render_template("professionals_list.html") (importantly, this does not inherit the main Jinja layout). Remember to pass in professionals=get_professionals() as a parameter.

Third, In index.js, add the following function to call on your new route (the code below assumes you called it "/professionals_refresh"):

index.js

Test this function in console mode to make sure it works as expected.

Step 5. Handle the API Response

Finally, in index.js, add the following to the bottom of your add_professional() function to refresh automatically on success and alert the user on failure:

index.js::add_professional()

Test the AJAX Form Application

Test your form by entering both invalid and valid form data. Check that it refreshes the professionals when the submission is successful and alerts the error when not.

You may notice that it would be more user-friendly to make the alert messages something more meaningful to the user rather than presenting cryptic API responses. You will do this in Project Part 4.5.