To start off, our goal is to simply display the data we need inside of a parent div container. I’ll also be using Laravel’s Blade templates, however, you can also use documents with the HTML extension. We would have a document with a structure similar to the image below:
After opening the link, just look for the section tailored specifically for jQuery, and you’ll see different code snippets that reference different jQuery versions. In this example, I’ll use the latest version which is 3.6.1, as of this date, and embed it in my file. The example below demonstrates how to embed it:
Now, we need to include jQuery’s ready() method that will execute our jQuery code after the DOM and the HTML document is loaded as shown below:
We will add the rest of our jQuery code within the ready() method, and we can continue by using the $.ajax() method to request data from the server. I want to send the request directly after the DOM is fully loaded. The syntax of the code will look similar below:
When sending a GET request, we need to fill-up a couple parameters inside the ajax method such as the type, url, datatype, and success. There are more parameters that we can add, but we will stick to these four useful parameters for now. If you need a reference for the complete parameters, I suggest checking the documentation with this link: https://api.jquery.com/jquery.ajax/
Provided below is each parameter used in the code along with its description:
type – optional parameter that indicates the type of request to be sent.
url – indicates the URL where the request will be sent to in the form of a string
dataType – specifies the expected response format or type of data.
success – indicates the code that will execute when the request succeeds.
Of course, we should always check if we are receiving data, so I added a console log method to verify if we are properly receiving the content we need. For the URL I’ve added, I simply generated a route that would display a list of pets in JSON format:
Finally, we will display the data on our web page by appending a div that holds the pet values associated to each key. Below is a simple example on how to do it by looping through each key and value within the pet JSON object.
And, voila! Here is the result when our code is executed:
I definitely enjoyed learning how to use jQuery and AJAX through the project and lessons given to me by Commude. I’m hoping to improve my skills even further by utilizing what I learned in my personal projects and researching more about the best practices. I hope you will feel the same as I do with the step-by-step tutorial I gave!