0

I want to submit a form using ajax post and avoid to refresh the page. I'm using Spring and Jquery.

Someone how can I submit the form over ajax and use the class in the controller to do stuff?

The model Class is Auction (the one I'm trying to submit):

public class Auction {

    private int id;
    private int userId;
    private String dateStart;
    private String dateEnd;
    private double maxPrice;
    private boolean payed;
    private boolean delivered;
    private boolean scheduledTaskParsed;
    private SimpleRegisteredUser user;
    private WantedProduct wantedProduct;
    (...)
}

and the WantedProduct class is

public class WantedProduct {
    private int id;
    private String title;
    private String description;
    private int userId;
    private int productStateId;
    private String stateDescription;
    private int productTypeId;
    private String brand;
    private String brandURL;
    (...)
}

The form to submit is:

<form:form id="new-auction" modelAttribute="auction" action="/product/create/" method="post" enctype="multipart/form-data">
    <form:hidden path="id"/>
    <form:input path="wantedProduct.title" id="title" maxlength="300" placeholder="${nameLabel}*"/>
    <form:input id="uploadFile" path="wantedProduct.photosWantedProduct[0].photo.photoFile" type="file"  accept="image/*"/>
    <form:select id="productTypeSelect" path="wantedProduct.productTypeId" >                                                                                                                        
         <c:forEach var="t" items="${types}">                                                                                                               
            <form:option value="${t.id}">
                <spring:message code="${t.description}"/>
            </form:option>
          </c:forEach>                                          
    </form:select>      
    <form:input path="wantedProduct.brand" id="brand" placeholder=""/>      
    <form:input path="maxPrice"/>                                                   
    <form:input path="wantedProduct.description"/>      
    <form:select path="wantedProduct.productStateId" >                                                                                                                      
         <c:forEach var="state" items="${productStates}">                                                                                                               
            <form:option value="${state.id}">
                <spring:message code="${state.description}"/>
            </form:option>
          </c:forEach>                                          
    </form:select>      

    (...)   
</form:form>

Thank you

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
amachado
  • 1,032
  • 1
  • 15
  • 31
  • 2
    Check this answer : [How to use Servlets and Ajax?](http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax#answer-4113258) – Kapouter Feb 26 '16 at 10:34

1 Answers1

0

After trying many solutions I figured out.

First I serialize the form:

var formFields = $('*:not(.no-serialize)', '#new-auction').serialize();

then I parsed this string to convert in an array like this:

var fieldArray = convertToArray(formFields);

function getUrlVars(url,isInt) {
    var hash;
    var myJson = {};
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if(hash[0] !='language'){                
            myJson = processsField(hash[0],hash[1],myJson,isInt);
        }           
    }
    return myJson;
}

function processsField(key,value,myJson,isInt){

    if(key.indexOf('.')>0){
        keys = key.split('.');
        myJson[keys[0]] = processsField(keys[1],value,myJson[keys[0]],isInt);
    } else{    
        if(myJson === undefined){
            myJson = {};
        }
        myJson[key] = value.length>0?(isNaN(value) || isInt.indexOf(key) < 0 ?value.toString():Number(value)):null;    
    }
    return myJson;
}

And last I call the ajax method:

$.ajax({
                  type: "POST",
                    global: false,
                  contentType : 'application/json; charset=utf-8',
                  //dataType:  "text",
                  //dataType : 'json',
                  url: '${urlAddr}',
                  data: JSON.stringify(fieldArray),
                  success :function(result) {                      
                      console.log("yupii... Success");                                 
                  },
                  error: function(objRequest ){     
                      console.log("error");
                      console.log(objRequest.responseText);  
                  }
              }); 

This way, the controller has the class Auction as input and everything works like a charm!!

Thanks for everything!!

amachado
  • 1,032
  • 1
  • 15
  • 31