Normal one
Normal one

Reputation: 145

Pass array to ajax request in $.ajax() to controller Spring mvc

I want to pass an array of strings as well as a string variable to the controller but it says parameter not present.

here is my javascript

function updateIssueHandler() {
var keyArray = [];
bootstrap_alert_hide('#form_errors');// cleans previous errors
$('input:checkbox[name=key_checkbox]:checked').each(function() {
    keyArray.push($(this).val())
});
if (keyArray.length == 0) {
    var errorMsg = document
            .getElementById("js.i18nMessage.emptyUpdateTickets.id").value;
    bootstrap_alert('#form_errors', errorMsg)
}
var labels = document.getElementById('labelsTextBox').value;
var b = {
    "lab" : labels,
    "keys": keyArray
};
//console.log(addl);
console.log(keyArray);
$.ajax({
    url : '/jirabatchapp/JqlUpdate/',
    data : b,
    type : 'POST',
    success : function(data) {
        window.alert("done");
    },
    error : function(e) {
        alert(JSON.stringify(e));
    }
});
}

Controller:

@Controller
public class UpdateLabelController {

@RequestMapping(value = "/JqlUpdate", method = RequestMethod.POST)
public String updateIssue(@RequestParam(value = "lab") String a,@RequestParam(value = "keys") String k ) {

    System.out.println(a);
    System.out.println(k);
    System.out.println("finally!");
    return "success";
}
}

I get an error saying HTTP request error 400 Required string parameter lab not present.

What am i doing wrong? if I only pass labs, then it works, but if i want to pass both parameters it is throwing me this error.

Upvotes: 2

Views: 1225

Answers (2)

Nimesh
Nimesh

Reputation: 802

change

var b = {
    "lab" : labels
    "keys": keyArray
};

to

var b = {
    "lab" : labels,
    "keys": keyArray
};

Upvotes: 2

Steeve Pitis
Steeve Pitis

Reputation: 4443

You have to pass a string as parameters

Just do this : data : JSON.stringify(b)

EDIT :

Try : data: $.param(b)

Upvotes: 0

Related Questions