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>