I'm trying to update by using PUT method. Where form doesn't support put method, I'm trying it through ajax call. I don't know how the backend will be getting the values through post call from form. I'm trying to implement the same using ajax.
Tried Map. But it's taking it as an object. And key value form is not happening.
Please help me to do so.
function updateRecord(divId)
{
var map = new Map();
var hiddenField;
var divNode = document.getElementById(divId);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i)
{
var inputNode1 = inputNodes[i];
var inputVale = inputNode1.value;
var inputName = inputNode1.name;
map.set = (inputName,inputVale);
}
let contextURL = 'http://localhost:8080/LocationWeb/LocCon/updateLocationValues/';
let parmURL = contextURL + map;
var xhr = new XMLHttpRequest();
xhr.open("PUT", parmURL, true);
xhr.send();
xhr.onload = function()
{
if (xhr.status != 200)
{
console.log('ERROR');
}
else
{
listAllPageCall();
}
};
xhr.onerror = function()
{
window.location = 'http://localhost:8080/LocationWeb/LocCon/listAllLocations';
};
}
My backed spring boot code is like this.
@PutMapping("/updateLocationValues")
public String updateLocationValues(@ModelAttribute("location") Location location, ModelMap resModMap)
{
locationService.updateLocation(location);
List<Location> allLocations = locationService.getAllLocation();
resModMap.addAttribute("allLocations", allLocations);
return "displayAllLocations";
}
UPDATE
Tried as mentioned by @Heretic Monkey
function updateRecord(divId)
{
var form = document.getElementById('updateTable');
var xhr = new XMLHttpRequest();
var formData = new FormData(form);
//open the request
xhr.open('PUT','http://localhost:8080/LocationWeb/LocCon/updateLocationValues')
xhr.setRequestHeader("Content-Type", "application/json");
var sendJs0n = JSON.stringify(Object.fromEntries(formData));
//send the form data
xhr.send(sendJs0n); //This acts a body message
form.onsubmit = function(event)
{
xhr.onreadystatechange = function()
{
if (xhr.readyState == XMLHttpRequest.DONE)
{
form.reset(); //reset form after AJAX success or do something else
}
}
//Fail the onsubmit to avoid page refresh.
return false;
}
}
Taking the jason value {"id":"1","code":"sfasdfas","name":"fdsafsdf","type":"RURAL"}
But not in backend application, its getting all null values.