This tutorial follows from Part 1.
In this tutorial, you would learn how to call the PHP API from a html page. We would use JQuery to make the REST API call. Then the data returned will be displayed on html page.
Note: Later I would show you an easier way to fectch MySQL data. That is using PDO. But for now, try learn how it works!
The three steps are:
1. Create the HTML Page
Inside the same folder as the services.php, create html file. Name it index.html
The file should have the following structure:
<html> <head> <title>Consume PHP Web Service</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script> // JQuery coded goes here </script> </head> <body> <div> <h2> List of Students </h2> <ol id="students"> <!-- list goes here --> </ol> </div> </body> </html>
2. Write the JQuery Script
Now, inside the second <Script></Script> tag, write the code to make a rest call to the services.php. The code fetches the data and encodes it as a json. Finally it appends it as <li></li> items to the students elements.
The full code is given below. You need to put this code in the <script></script> tag.
// JQuery coded goes here $.get("http://localhost/demoweb/services.php", function(data, status){ // Parse the data and save it in studentList variable var studentList = JSON.parse(data); for(var i = 0; i < studentList.length; i++) { var student = "id: " + studentList[i].id + " firstname: " + studentList[i].firstname + " lastname: " + studentList[i].lastname + " location: " + studentList[i].location; //add the item to page as list items <li> student = "<li>" + student + "</li>"; $("#students").append(student); } });
3. Test the API
At this point, you can copy over the files to the server folder. We created this folder in Part 1.
Open the browser and visit, http://localhost/demoweb/index.html
You will see the list of items fetched from the database as shown below
Next Steps
Next, we would write a PHP method to make a POST request. This would insert an student record into the MySQL database.
One thought on “GET Request to PHP API Using JQuery – Part 2”