Santosh Jadi Santosh Jadi - 7 months ago 20
Javascript Question

Pass Multiple data variables to the AJAX function in an easy way?

I have something around 15 - 20 data variables, to pass through below ajax function.

Is there any best easy way to pass multiple variables from ajax and get the those multiple variables in below Controller Class in an easy way??

Jsp page:

function getAssignedParticularTable(){
$.ajax({
type: "POST",
url: "assignedParticularTable.html",
data: "operation=assignedParticularTable",
success: function(response){
var obj = JSON.parse(response);
$("#table2").html("");
var tr="";
tr+="<thead><tr><th>Sl no.</th><th>Fee Particular Name</th><th>Amount</th><th>Selection</th></tr></thead><tbody>";
for (var i = 0, j=0; i < obj.length; i++){
tr+="<tr>";
tr+="<td>" + (++j) + "</td>";
tr+="<td>" + obj[i].Name + "</td>";
tr+="<td><input type='text' id='amount' name='amount' value='0'/></td>";
tr+="<td><input type='checkbox' id='check' name='fee_particular_ids' value='"+obj[i].Id+"' /></td>";
tr+="</tr>";
}
$("#table2").append(tr);
}
});
}


Controller Class:

@RequestMapping(value = "/assignedParticularTable.html", method = RequestMethod.POST)
public @ResponseBody String assignedParticularTable(@RequestParam HashMap<String, String> map, HttpSession session) {

System.out.println("operation: " + map.get("operation"));

return "";
}

Answer

JSP Page:

    function getAssignedParticularTable(){
        $('#result2').hide();   
        var jsonValues = {paymentType : $('#paymentType').val(), subPaymentType : $('#subPaymentType').val()};
        $.ajax({
            type: "POST",
            url: "assignedParticularTable.html",
            contentType : 'application/json; charset=utf-8',
            data: JSON.stringify(jsonValues),
            success: function(response){

            }
        });
    }

Controller Class:

@RequestMapping(value = "/assignedParticularTable.html", method = RequestMethod.POST)
public @ResponseBody String assignedParticularTable(@RequestBody HashMap<String, String> jsonValues, HttpSession session) {
    System.out.println("operation: "+jsonValues); 
    System.out.println("operation1: "+jsonValues.get("paymentType"));           
    return "";
}
Comments