In Supporting CRUD Operations, we fetched object data via HTML links. That worked well enough, but the data was not processed on the client-side in any way, so that the JSON data was displayed in its raw form:
Let’s update the index.html page to display the vehicle data in a more meaningful way.
To begin with, we’ll create a whole new index.html file where the links point to the server that we created in the Supporting CRUD Operations tutorial. Here’s the markup for that so far:
Important: if you did not enable CORS on the server, you will get a “CORS header ‘Access-Control-Allow-Origin’ missing” error when you contact the server on a different domain. The following code lets the server tell the browser it’s permitted to use an additional origin:
Next, we’ll intercept the link navigation and call the server endpoint via AJAX so that we can remain on the page and display the vehicle data in a form:
Here is the markup for our form:
As it happens, I mapped the form field names to those of the JSON object so that we can simply iterate over each to fetch the corresponding JSON attribute:
Sometimes it’s not enough to set the form contents. For updates and exceptions, you will want to notify the user of success or failure. We’ll add a label above the form for that purpose, along with a function that sets the message:
In addition to setting the label value, the showUserMessage() function, shown below, also clears the message after 5 seconds, so that the message is only shown while it is relevant to the previous action:
Now we can call showUserMessage() from our AJAX success and failure handlers:
In a real application, one might set different classes on the message label to distinguish errors from success notifications, but that’s beyond the scope of this article.
This time around, form fields – with the exception of the ID – are editable, so we can update their values in place. When we’re ready we can submit the form contents by clicking a button that we can place at the bottom of the form:
The button click invokes the following handler:
Rather than delete a specific vehicle, as we did previously, now the Delete button applies to whatever vehicle is currently displayed in the form. Here is the button markup:
The code that invokes the API is very similar to that of the update, with two major differences:
The original home of HTML tutorials
Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.