This tutorial follows from Part 1 and Part 2
Part 1 – Create a REST API in PHP
Part 2 – Make a GET API Request Using JQuery
You will learn how to write a method that makes a POST Request to the PHP REST API we created.
So we’ll cover the following:
1. Create the HTML Form
Open the index.html for we created in Part 2
Create the html for with 3 inputs textboxes and on Submit button. I have put this codes inside a <div></div> tag,
The complete code for the form is given below:
<div id="insertDiv"> <h2>Insert New Student</h2> <label>Firstname: </label> <input type="text" id="txtFirstname" /><br> <label>Lastname: </label> <input type="text" id="txtLastname" /><br> <label>Location: </label> <input type="text" id="txtLocation" /><br> <br> <input type="button" id="saveStudent" value="Save Student" /> </div>
2. Write the JQuery Method
At this point, we would now write a JQuery method the performs the POST request. This method runs on button-click for the “saveStudent” button.
Remember that to select the button, you use the # selector. So it would be #saveButton.
$("#saveStudent").click(function(){ console.log("Inserting data...") var fname = $("#txtFirstname").val(); var lname = $("#txtLastname").val(); var lctn = $("#txtLocation").val(); //Create a new Student object using the values from the textfields var student = { firstname : fname, lastname : lname, location : lctn }; //Make the POST request using $.post() to the same url $.post("http://localhost/demoweb/services.php", student, function(data){ console.log(data); }); });
The code above would be inside the document.ready() function. But after the code for the GET request.
3. Modify the services.php File
Now, we need to modify the services.php file to also accept a post request. So we would use an if statement to check the request method. If the method is GET, then we execute existing code, but if it it POST, we execute the code for handling POST.
The entire content of the services.php file is given below. I have used comments to separate different sections
<?php $url = "localhost:3301"; $database = "demodb"; $username = "root"; $password = "root"; $conn = mysqli_connect($url, $username, $password, $database); if(!$conn) { die("Unable to connect: " . $conn->connect_error); } $method = $_SERVER['REQUEST_METHOD']; if($method == "GET") { //************** START OF GET REQUEST ************ $sql = "SELECT * FROM demodb.tblusers"; $results = mysqli_query($conn, $sql); $rows = array(); if(mysqli_num_rows($results) > 0){ while($record = mysqli_fetch_assoc($results)) { array_push($rows, $record); } print json_encode($rows); } else { echo("No records found"); } } //*********** END OF GET REQUEST ************* else if($method == "POST") { $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $location = $_POST["location"]; $sql_insert = "INSERT INTO demodb.tblusers(id, firstname, lastname, location) VALUES (0, '$firstname', '$lastname', '$location')"; if(mysqli_query($conn, $sql_insert)) { echo "Student data was succesfully inserted into the database!"; } else { echo "Error occured. Data was not insered : ". mysqli_error($conn); } } mysqli_close(); ?>
4. Test the API
You can now upload all the files to the server.
Then visit http://localhost/demoweb/index.html
You will see the form as shown below.
Fill up the form and submit. Then refresh the page to see the new data submitted. If it works, thumbs up to you!
5. Next Steps
If you completed this part, then congrats!
Next, we would learn how to make a PUT request and a DELETE request.
Finally, we would now go on to see how to do all this an easy way!