Ajax call with Spring MVC Controller I have been woring on AJAX and JQuery site. Here is my simple implemtation. i am looking forward to getting your reviews for any improvement/replacement for code mentioned below.


  Brief explanation: when someone want to submit the form with specified ID, all form fields are assigned to appropriate variables. After that a new JSON document is generated based on the form field variables. Then AJAX call is performed. It directed to URL which is specified in the action attribute of form tag. The JSON is used as a data which need to be processed. Type of the request is POST (it can vary depending on operation, e.g. for update it will has PUT value).


   &lt;html&gt;
    &lt;head&gt;
        &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;input name="search" type="text" maxlength="100" id="search"/&gt;

        &lt;button onclick="searchID()"&gt; Search ID &lt;/button&gt;
        &lt;button onclick="getAll()"&gt; Get All &lt;/button&gt;

        &lt;p&gt; Id: &lt;input name="search" type="text" maxlength="100" id="userId"/&gt;&lt;/p&gt;
        &lt;p&gt; First name: &lt;input name="search" type="text" maxlength="100" id="fName"/&gt;&lt;/p&gt;
        &lt;p&gt; Last name: &lt;input name="search" type="text" maxlength="100" id="lName"/&gt;&lt;p&gt;


        &lt;button onclick="save()"&gt; Save &lt;/button&gt;

        &lt;div id="customers"&gt;&lt;/div&gt;

        &lt;script&gt;

                function searchID()
            {
                var id = document.getElementById("search").value;
                $("#customers").html("");


                $.getJSON("http://localhost:8080/customer/" + id,  function(data)
                {

                        $('#customers').append("&lt;p&gt;ID: " + data.userId + "&lt;/p&gt;")
                        $('#customers').append("&lt;p&gt;First name: " + data.fName + "&lt;/p&gt;")
                        $('#customers').append("&lt;p&gt;Last name: " + data.lName + "&lt;/p&gt;&lt;br&gt;")


                });


            }

            function addCustomer()
            {
                var customerInfo = {
                    id: document.getElementById("id").value,
                    fName: document.getElementById("fName").value,
                    lName: document.getElementById("lName").value

                }


                $.ajax({
                    url: "http://localhost:8080/customer/", 
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify(customerInfo)
                });
            }





            function getAll()
            {
                $("#customers").html("");

                $.getJSON("http://localhost:8080/customers/",  function(data)
                {
                    for (var i in data) {
                        $('#customers').append("&lt;p&gt;ID: " + data[i].id + "&lt;/p&gt;")
                        $('#customers').append("&lt;p&gt;First name: " + data[i].fName + "&lt;/p&gt;")
                        $('#customers').append("&lt;p&gt;Last name: " + data[i].lName + "&lt;/p&gt;&lt;br&gt;")
                    }
                });
            }
        &lt;/script&gt;
    &lt;/body&gt;
    &lt;/html&gt;
I think you just can get rid of getAll() function as it is just a special case of searchID().

 function searchID() {
     var id = document.getElementById("search").value;
     $("#customers").html("");

     $.getJSON("http://localhost:8080/customer/" + id,  
       function(data) {
                 ([].concat(data)).forEach(function(customer) {
                     $('#customers').append("&lt;p&gt;ID: " + customer.userId + "&lt;/p&gt;");
                     $('#customers').append("&lt;p&gt;First name: " + customer.fName + "&lt;/p&gt;");
                     $('#customers').append("&lt;p&gt;Last name: " + customer.lName + "&lt;/p&gt;&lt;br&gt;");
                 });   
       });
  }


If the id value is empty then the results it's exactly the same as getAll().

Another important thing to change is the url, if your server is the same, you can just remove the initial part:

$.getJSON("/customer/"...);


This helps to avoid bugs in the future or need of refactoring if you just simply add https.

Cache the jQuery search to avoid the repeat:

 function searchID() {
     var $customers = $("#customers");
     var id = document.getElementById("search").value;
     $customers.html("");

     $.getJSON("http://localhost:8080/customer/" + id,  
       function(data) {
                 ([].concat(data)).forEach(function(customer) {
                     $customers.append("&lt;p&gt;ID: " + customer.userId + "&lt;/p&gt;");
                     $customers.append("&lt;p&gt;First name: " + customer.fName + "&lt;/p&gt;");
                     $customers.append("&lt;p&gt;Last name: " + customer.lName + "&lt;/p&gt;&lt;br&gt;");
                 });   
       });
  }


Here is an example inside the searchID() function, if you use in all the module, you should save as a module variable.

Another thing is that is not responsability of searchID() to know how to get the id:

 function searchID(id) {
     var $customers = $("#customers");
     $customers.html("");

     $.getJSON("http://localhost:8080/customer/" + id,  
       function(data) {
                 ([].concat(data)).forEach(function(customer) {
                     $customers.append("&lt;p&gt;ID: " + customer.userId + "&lt;/p&gt;");
                     $customers.append("&lt;p&gt;First name: " + customer.fName + "&lt;/p&gt;");
                     $customers.append("&lt;p&gt;Last name: " + customer.lName + "&lt;/p&gt;&lt;br&gt;");
                 });   
       });
  }


Instead you should add a new function:

function performSearch() {
    var id = document.getElementById("search").value;
    searchID(id);
}


And the same for the draw of the customers on the page:

function displayCustomers($el, customers) {
    $el.html("");

    customers.forEach(function(customer) {
           $el.append("&lt;p&gt;ID: " + customer.userId + "&lt;/p&gt;");
           $el.append("&lt;p&gt;First name: " + customer.fName + "&lt;/p&gt;");
           $el.append("&lt;p&gt;Last name: " + customer.lName + "&lt;/p&gt;&lt;br&gt;");
    });
}


And then:

function performSearch() {
    var id = document.getElementById("search").value;
    searchID(id, function(customersToDisplay) {
        displayCustomers($("#customers"), customersToDisplay);
    });
}


And the new searchID():

 function searchID(id, callback) {
     $.getJSON("/customer/" + id,  
       function(data) {
           callback(([].concat(data));
       });
  }


In this way you separate the different aspects:


handle the dom event and launch a command accordingly;
perform an ajax request and handle the harmonization of the response.
use a callback to handle the ajax response
update the DOM