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.
change
var b = {
"lab" : labels
"keys": keyArray
};
to
var b = {
"lab" : labels,
"keys": keyArray
};
You have to pass a string as parameters
Just do this : data : JSON.stringify(b)
EDIT :
Try : data: $.param(b)
Related
I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.
This is in continuation with one of the previous questions
I have a OData Controller with the Action as :
[HttpPost]
[ODataRoute("PostUpdate")]
public async Task<string> PostUpdate(HttpRequestMessage eventsToUpdate)
{
//Do something
}
This is how I am calling the controller through the ajax call:
var eventsToUpdate = [];
for(i=0;i<5;i++)
{
//Build the data
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
eventsToUpdate.push(updatedT);
}
Url = "Api/Odata/PostUpdate"
$.ajax({
url :Url,
type:"POST",
data:eventsToUpdate ,
dataType : 'json',
success : function(result) {
}
});
The problem is even after converting an array to json , the data is not available in the controller's action. This is what I did
var eventsToUpdate = JSON.stringify(eventsToUpdate);
But if I just pass
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
I get the same data in action . What is the solution for this?
What seems to me your [HttpPost] is expecting a key named eventsToUpdate but it doesn't find in the posted request as it is not there because of:
data:eventsToUpdate , // which is eq to = data:[{},{}...],
better to send an object like:
data:{eventsToUpdate:eventsToUpdate} ,
//----^^^^^^^^^^^^^^---------this key will be captured at backend
contentType:'application/json', //<------you would need to add this
and another suggestion is to use traditional:true, if required.
Also, async Task<string> if return type is string then you need to change the dataType of the ajax too or you should return json from the WebMethod.
I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})
I am trying to pass long array from jquery load to spring controller. How can i sent js object array t spring mvc controller.
Every time action occured the no data alert on script will called.
Script
var arr = [];//Array
$(document).ready(function() {
$(".rating").click(function() {
var idx = $(this).closest('td').index();
var userskill = {//Object
tech : $(this).closest('td').siblings('td.tech').text(),
skill : $('#listTable thead th').eq(idx).text(),
rValue : $(this).val()
}
add(userskill);
});
});
function add(userskill) {
arr.push(userskill);
$.ajax({
type : 'POST',
dataType : 'json',
url : '/SimplWebApp/saveUserRating',
data : ({
id : JSON.stringify(arr)
}),
success : function(responseData) {
if (responseData != null) {
alert(responseData);
} else {
alert("no data");
}
}
});
}
controller
#RequestMapping(value = "saveUserRating")
public #ResponseBody String saveUserRating(#RequestParam(value="id[]", required=false) String[] x) {
Gson gson = new Gson();
String data = gson.toJson(x);
return data;
}
The JSON array resides in the body of the request. You can use the #RequestBody annotation to obtain the array if you have Jackson on the classpath to deserialize the JSON.
saveUserRating(#RequestBody(required=false) String[] ids)
If you want to use the array as the response body simply return the array from the handler method. It will be serialized to JSON automatically.
#ResponseBody
public String[] saveUserRating(saveUserRating(#RequestBody(required=false) String[] ids)) {
return ids;
}
I have a generic dispatcher that takes in parameters and then make $.ajax()
As you can see, I am looping through the parameters to build the data.
function dispatch(controller, action, param1, param2,...) {
var args = '', pg = 1, id = '';
var l = arguments.length;
var data = {};
for (var i = 2; i < arguments.length; i += 2) {
data[arguments[i]] = arguments[i + 1];
}
$.ajax({
type: "POST",
url: "/" + (controller + "/" + action,
data: data,
dataType: "json",
success: function (res) {
alert('success');
},
error: function (xhr, status, error) {
alert('error!');
}
});
}
This is how I call:
dispatch("XYZ", "AddGuests", "id", 10, "name", "Bob");
Everything works as expected and I get all parameters back in my MVC 3 controllers.
Now I need to pass multidimentional associative array as parameter to my controller.
I want to use the single generic dispatcher I use for other calls.
But somehow I am getting null for the associative array parameter.
Basically I want to post a guests array to my controller's List parameter.
Code to prepare the associative array data:
var guest = {};
var guests = [];
for(var i=0;i<2;i++){
var name = GetName();
var email = GetEmail();
guest = { 'Email': email, 'Name': name };
guests.push(guest);
}
End of the loop would give me, say:
{
{'Email':"bob#zyz.com", 'Name':"Bob"},
{'Email':"tom#zyz.com", 'Name':"Tom"}
}
This is the new call to the dispatcher:
dispatch("XYZ", "AddGuests", "id", 10, "guests", JSON.stringify(guests));
This is my controller:
[HttpPost]
public ActionResult AddGuests(string id, List<SelectedGuest> guests){
//save guests
}
[Serializable]
public class SelectedGuest
{
public string Email { get; set; }
public string Name { get; set; }
}
When I look at httpfox I see correct values posted:
id 10
guests [{"Email":"bob#zyz.com","Name":"Bob"},{"Email":"tom#zyz.com","Name":"Tom"}]
If I do this, I get the guest passed correctly to my controller:
But this limits me to pass just the guests array not other parameters.
data = JSON.stringify(guests);
What I am doing wrong? Thanks for reading.
If using JSON.stringify(guests) works, why not combine it into another JSON object with your other parameters that don't need stringification?
data = { "id": 10, "Guests": JSON.stringify(guests) };
Alternatively, you could construct a javascript object that combines these and call stringify on that.