HTTP POST data to an API

Published on: September 2, 2018

Welcome to the 16th Easy jQuery tutorial! We are still on AJAX and today we cover the HTTP POST method with $.ajax()

POST allows you to send data to an API end point as a "write" - meaning you are asking the server to add new data. This is the C in CRUD. Create. 

Sure, you can send data to be written using GET, but using HTTP POST is also much safer than using GET because the data is not being sent via the URL query string, instead it's being sent in the body of the request. It ensures no one can read the sent request easily. 

Here's a quick example of the HTTP POST used in the video:

 
    $.ajax({
        url: 'http://localhost:3000/api/tutorials',
        method: 'POST',
        dataType: 'json',
        data: {
            tutorialNumber: 4,
            title: 'fourth tutorial',
            author: 'Nazmus',
            type: 'Excel'
        }, success: function(data) {
                console.log(data);
                getTutorials();
            }
     });

The properties of $.ajax() is the same as GETting data. The only difference is that the method has been changed to POST, and we are sending more data back to write to the database. 

Check out the AJAX GET tutorial for an explanation of all the properties.

You can use the following Easy Programming dummy JSON file for practice: https://www.easyprogramming.net/heroes.json

I hope you enjoyed this tutorial! Please feel free to ask questions below or just leave your comments.

Since this tutorial was done in Brackets, there is no JS Fiddle. This description will be updated after the AJAX series has been completed and I've uploaded the files in the resources section below. 

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:

You can find the entire HTML and JavaScript files at the following URL: https://www.easyprogramming.net/downloads/jquery/crudApp/

You can get the source HTML out of that page and if you are having trouble finding the JavaScript, find it at the following URL: https://www.easyprogramming.net/downloads/jquery/crudApp/script.js



Comments: