Save data [POST] using Java Web Services and jQuery Ajax

Hi guys, Bushan here, welcome back to B2 Tech! Today in this article I will teach you how to make POST request using jQuery Ajax, so let’s get started! To make POST request, I have already created a Java web service, I will use the same web service in this article.



http://localhost:8037/spring-mvc-restfull-crud-example/book

I have created this web service using Spring REST. To make a POST request on this web service, we need to POST a JSON data to this web service. I have already created a table in the database. We have 3 columns, Id, Title and Author, where Id is the Primary key. We will send the book title and author name in JSON format, and it will submit the data to the database.

NOTE: I have created this web service using Spring REST but you can create using any server-side technology.

Now let’s design a web page where the user will enter the book title and author name and when they click the submit the button we will make POST request on the web service using jQuery Ajax.

index.html

<html>
   <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script type = "text/javascript">
         $(document).ready(function () {
             var book = {};
             $('#btnAddBook').click(function () {
                 book.title = $('#txtName').val();
                 book.author = $('#txtAuthor').val();
                 var bookJSON = JSON.stringify(book);
                 $.ajax({
                     url: 'http://localhost:8037/spring-mvc-restfull-crud-example/book',
                     method: 'POST',
                     data: bookJSON,
                     contentType: "application/json; charset=utf-8",
                     success: function () {
                         alert('Saved successfully!');
                     },
                     error: function (error) {
                         alert(error);
                     }
                 })  
             })
         });
      </script>
   </head>
   <body>
      <table border="1" style="border-collapse:collapse">
         <tr>
            <input id="txtId" type="text" hidden/>
            <td>Book Name</td>
            <td><input id="txtName" type="text" /></td>
         </tr>
         <tr>
            <td>Author</td>
            <td><input id="txtAuthor" type="text" /></td>
         </tr>
         <tr>
            <td colspan="2">
               <input type="button" id="btnAddBook" value="Add Book" />
            </td>
         </tr>
      </table>
   </body>
</html>



At this point test your work by running the file in a web browser, POST the below JSON data to the web service. if you see the alert message saying saved successfully then the application is working fine.

{
	"title" : "The Laughing Monsters",
	"author" : "Denis Johnson"
}

Next step is to display all the records in HTML table just below the form as soon as the user submits the form. This will help the user to view all the books in the HTML page itself.

We will use the same approach as we discussed in our previous article, we will make GET request using jQuery Ajax.

Here is the complete source code of it,

<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Page Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type = "text/javascript">
            $(document).ready(function () {
                var employee = {};
                getAllBooks();
                $('#btnAddEmployee').click(function () {
                    employee.title = $('#txtName').val();
                    employee.author = $('#txtAuthor').val();
                    var employeeJSON = JSON.stringify(employee);
                    $.ajax({
                        url: 'http://localhost:8037/spring-mvc-restfull-crud-example/book',
                        method: 'POST',
                        data: employeeJSON,
                        contentType: "application/json; charset=utf-8",
                        success: function () {
                            alert('Saved successfully!');
                            getAllBooks();
                        },
                        error: function (error) {
                            alert(error);
                        }
                    })
                    
                })
            });
            
            function getAllBooks() {
                $.ajax({
                    url: 'http://localhost:8037/spring-mvc-restfull-crud-example/book',
                    method: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        var tableBody = $('#tblEmployee tbody');
                        tableBody.empty();
                        $(data).each(function (index, element) {
                            tableBody.append('<tr><td>'+element.title+'</td><td>'+element.author+'</td>');
                        })
                    },
                    error: function (error) {
                        alert(error);
                    }
                });
            }
        </script>
    </head>
    <body>
        <table border="1" style="border-collapse:collapse">
            <tr>
                <input id="txtId" type="text" hidden/>
                <td>Book Name</td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td>Author</td>
                <td><input id="txtAuthor" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" id="btnAddEmployee" value="Add Employee" />
                </td>
            </tr>
        </table>
        <table id="tblEmployee" border="1" style="border-collapse:collapse">
            <thead>
                <tr>
                    <th>Book Name</th>
                    <th>Author</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </body>
</html>



So now let’s open the file in a browser and you will see the following page. If you see the following page then congratulations you made it.



That’s it for this article, I hope this article is helped you in one or the other way if you have questions leave your questions in the comment section, I will try to answer it. In the next article we will discuss DELETE request/deleting a record. If you like this article, do share this with your friends and colleagues, i will see in the next article.

 

About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *