1
\$\begingroup\$

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).

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

        <button onclick="searchID()"> Search ID </button>
        <button onclick="getAll()"> Get All </button>

        <p> Id: <input name="search" type="text" maxlength="100" id="userId"/></p>
        <p> First name: <input name="search" type="text" maxlength="100" id="fName"/></p>
        <p> Last name: <input name="search" type="text" maxlength="100" id="lName"/><p>


        <button onclick="save()"> Save </button>

        <div id="customers"></div>

        <script>

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


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

                        $('#customers').append("<p>ID: " + data.userId + "</p>")
                        $('#customers').append("<p>First name: " + data.fName + "</p>")
                        $('#customers').append("<p>Last name: " + data.lName + "</p><br>")


                });


            }

            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("<p>ID: " + data[i].id + "</p>")
                        $('#customers').append("<p>First name: " + data[i].fName + "</p>")
                        $('#customers').append("<p>Last name: " + data[i].lName + "</p><br>")
                    }
                });
            }
        </script>
    </body>
    </html>
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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("<p>ID: " + customer.userId + "</p>");
                     $('#customers').append("<p>First name: " + customer.fName + "</p>");
                     $('#customers').append("<p>Last name: " + customer.lName + "</p><br>");
                 });   
       });
  }

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("<p>ID: " + customer.userId + "</p>");
                     $customers.append("<p>First name: " + customer.fName + "</p>");
                     $customers.append("<p>Last name: " + customer.lName + "</p><br>");
                 });   
       });
  }

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("<p>ID: " + customer.userId + "</p>");
                     $customers.append("<p>First name: " + customer.fName + "</p>");
                     $customers.append("<p>Last name: " + customer.lName + "</p><br>");
                 });   
       });
  }

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("<p>ID: " + customer.userId + "</p>");
           $el.append("<p>First name: " + customer.fName + "</p>");
           $el.append("<p>Last name: " + customer.lName + "</p><br>");
    });
}

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.