0

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.

S14321K
  • 220
  • 3
  • 19
  • You need to understand that when requesting using POST, you need to send a body which in this case should be json stringified string. The server gets this on the request object. URL params work in case of get requests. – Saqlain Jun 08 '23 at 16:47
  • A `Map` is not currently serializable with JSON. Also, the code is incorrect for using a `Map`; you would call `map.set(inputName, inputVale);` since `set` is a method. You also don't provide the map in the body, but rather try to append it to the URL. Pass the map as the argument to `send`. – Heretic Monkey Jun 08 '23 at 16:48
  • @HereticMonkey should I set the size of the map? And also I couldn't see the `Key`. I can see only the `value`. That too only one value is there. Should I use the Map or has to create a json type insteed? – S14321K Jun 08 '23 at 16:52
  • Does this answer your question? [How to send a JSON object using html form data](https://stackoverflow.com/questions/22195065/how-to-send-a-json-object-using-html-form-data) – Heretic Monkey Jun 08 '23 at 16:54
  • As I said, `Map` is not serializable; use an object. See the duplicate. – Heretic Monkey Jun 08 '23 at 16:54
  • But the json should be created dynamicaly. But there they hard coded the values. – S14321K Jun 08 '23 at 16:57
  • 1
    No, they didn't. Even in the accepted answer they use jQuery's `serializeArray` method, which dynamically extracts the names and values of the form elements. [This answer](https://stackoverflow.com/a/69374442/215552) does it with the `FormData` API if you aren't using jQuery. – Heretic Monkey Jun 08 '23 at 17:04
  • Its converting into json. But at at back end I'm getting null values. `Location{id=0, code='null', name='null', type='null'}` But I can see in ajax `"{"id":"1","code":"sfasdfas","name":"fdsafsdf","type":"RURAL"}"` – S14321K Jun 08 '23 at 18:05

1 Answers1

-1

fetch api

async function postData(url = "", data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: "PUT", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, *follow, error
    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • This is not an answer. Except for a game of buzzword bingo. Along with a copy-paste of documentation. If you want to answer with how to use the Fetch API to perform a PUT request, do so (or close the question as one of the many duplicates that we have of such a question). – Heretic Monkey Jun 08 '23 at 16:52
  • The posted answer illustrates issuing a PUT request. The question is How to do PUT request in JavaScript? – Ronnie Royston Jun 08 '23 at 17:01
  • Of which we have multiple duplicates. – Heretic Monkey Jun 08 '23 at 17:06