0

I am using JavaScript in JSP. I can send the formData to Spring Controller with <form action> but I needed to send through Ajax now. I am not using JQuery or AngularJS or any other JS framework.

my Form here is:

<form:form  id="saveAddressForm" modelAttribute="address">
    <tr>
        <td><label>Address1</label></td>
        <td><input type="text" name="addressLine1"></td>
        <td><label>Address2</label></td>
        <td><input type="text" name="addressLine2"></td>
    </tr>
    <tr>
        <td><label>LandMark</label></td>
        <td><input type="text" name="londMark"></td>
        <td><label>City</label></td>
        <td><input type="text" name="city"></td>
    </tr>
    <tr>
        <td><label>Pincode</label></td>
        <td><input  type="number" name="pincode"></td>
        <td></td>
        <td><input type="submit" value="Save Addess" onsubmit="saveAddress()"></td>
    </tr>
</form:form>

JS function:

function saveAddress(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        // On success i need to display a message.
    }
  };
xhttp.open("POST", "add_address.html", true);
xhttp.send();}

Here, my formdata ie.,Address object not including in request.

@RequestMapping(value = "/add_address", method = RequestMethod.POST)
public String addAddress(@ModelAttribute("address") Address address, Model map)
{

    // Services will be called here.
    return null;
}

I think, I am missing something to add my object to request.

I see couple of posts in SOF, they solved with JQuery or AngularJS. I am not aware of these.

Edit

Thinking how to improve my question. I want "modelAttribute" to send to controller. Not individual param nor through JS frame works.

CHowdappaM
  • 1,456
  • 1
  • 11
  • 30

2 Answers2

1

What is the problem ?

You need to add the parameters to build the Adress object.

See Send POST data using XMLHttpRequest

Community
  • 1
  • 1
J.Mengelle
  • 325
  • 2
  • 10
0

You can use jquery to easily serialize form data and pass with request.

Here is the modified code with jquery.

function saveAddress(){
    var xhttp = new XMLHttpRequest();
    var form = document.getElementById('saveAddressForm');
    var data = new FormData(form);
    xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        // On success i need to display a message.
    }
  };
xhttp.open("POST", "add_address.html", true);
xhttp.send(data);}
Mihir Gohel
  • 316
  • 2
  • 6