...

/

POST Request to REST API

POST Request to REST API

Learn to send a POST request to create a lecture post in the database.

We have added functionality to edit and delete lecture posts that are added from the admin dashboard. Now we will set up the code to add a new note from the frontend. To add a note, we will provide a form with title and content input elements. The users will click the Create button which will add the post to the database as well as show it on the frontend on the fly.

Create a form

Open the page-lecture-notes.php file. We will create a form above the list of posts, but inside the <div> with class generic-content. The form is placed in a <div> with class add-lecture. It has an input and textarea element as well as a <span> for the Create button.

<div class="generic-content">
<div class="add-lecture">
<h2>Add New Lecture Note</h2>
<input placeholder="Title">
<textarea placeholder="Type here..."></textarea>
<span> Create</span>
</div>
<ul class="list-item" id="lectures">
</ul>
</div>
Creating a form

For styling purposes and to target these elements in JavaScript, we will give these elements some CSS classes. We will give the create button a font-awesome icon of fa-plus-square.

<div class="add-lecture">
<h2 class="lecture-title">Create a lecture note:</h2>
<input class="new-lecture-title" placeholder="Title">
<textarea class="new-lecture-body" placeholder="Lecture Content"></textarea>
<span class="submit-lecture create-lecture"><i class="fa fa-plus-square" aria-hidden="true"></i> Create</span>
</div>
Styling the form

Add a post to database

Open the Lecture.js file. We will begin by creating a new event listener for the Create button.

With the Excellence folder open in VS Code, access the terminal by clicking the "View" option and choosing "Terminal." Run the start script using the npm run start command. The start script will watch for any changes in the code and recompile it.

The createButton property contains the ...