I am trying to pass an array of JS objects with 5 variables in the in the object.
When trying to get the array of objects in the java servlet I keep getting a NULL.
Passing a single variable or an object of variables works perfectly.
Java Servlet:
String [] s = req.getParameterValues("json[]");
I have also tried
String [] s = req.getParameterValues("json");
I added the [] because of this answer.
JavaScript code:
var list = [];
$(x).each(function(index, e) {
var y = $(e).find("input[id*='numOfShares']");
var id = y.attr('name');
var num = y.val();
var price = y.val();
var date = y.val();
var symbol = $("#holdSymb").val();
var hold = {
"holdingsID" : id,
"symbol" : symbol,
"purchasePrice" : price,
"numberOfShares" : num,
"purchaseDate" : date
};
list.push(hold);
});
$.ajax({
url:"URL",
type:"POST",
dataType:'json',
data: {json:list},//Also tried {'json':list},
success:function(data){
console.log("Done");
},
fail:function(data) {
console.log("Failed");
}
});
Related
I have an associative array
var order = [];
order['id'] = 1266;
order['customer'] = [];
order['customer']["firstName"] = "John";
order['customer']["lastName"] = "Doe";
order['customer']["age"] = 46;
I want to send this array as data into my ajax call
$.ajax({
url : 'http:example.com',
method : 'post',
dataType : 'json',
data : order,
success : function() {
}
})
Ajax are calling my url properly but sending empty data. I have tried
JSON.stringify(order)
data : {'order' : order}
data : {'order' : JSON.stringify(order)}
But none of these are working
You just need to change the array to object. Instead of var order = []; use var order = {};
I have a form and i wanted specific elements of the form which I got and stored the values in an array.
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var item_name = miniform.elements['itemId'].value;
var quantity = miniform.elements['quantityId'].value;
var amount = miniform.elements['amountId'].value;
var total = amount * quantity;
var cart = ["Item: ",item_name,"Quantity: ",quantity,"Amount: ",amount,"Total: ",total];
I would then like to convert this array into a JSON object and send it to a php file through ajax but its not working. Here is my ajax code:
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.stringify(cart),
success: function(){
console.log('Message Sent');
}
});
What could be the problem??
look the comma, it should be {"key":value, "key":value..} not {"key":,value, "key":,value..}
var cart = {"Item" : item_name, "Quantity" : quantity, "Amount" : amount, "Total" : total};
you are doing wrong .
please use this way
var cart = {"Item ":item_name,"Quantity ":quantity,"Amount ":amount,"Total ":total};
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.parse(cart),
success: function(){
console.log('Message Sent');
}
});
If you want to post the array Then you can use this way.
cart = [];
cart[0] = item_name;
cart[1] = quantity;
cart[2] = amount;
cart[3] = total;
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data:{cart:cart},
success: function(){
console.log('Message Sent');
}
});
Don't build it manually
Instead of building your Object or Array manually, which is prone to errors, do it like this:
Object
// Define your empty Object
var cart = {};
// Assign its properties
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = amount * quantity;
Array
Or if you prefer to have an array:
// Define your empty array
var cart = [];
// Assign its properties
cart['item_name'] = miniform.elements['itemId'].value;
cart['quantity'] = miniform.elements['quantityId'].value;
cart['amount'] = miniform.elements['amountId'].value;
cart['total'] = amount * quantity;
Now you have your cart Object or Array ready and you can call JSON.stringify on it:
JSON.stringify(cart);
You could just send the entire form using formdata(). Is there a reason you don't?
Anyway, it doesn't work because you are not creating a json object, but a normal array. There's a difference. You can actually just put the json directly into the ajax call and you don't have to stringify it.
var cart = {};
cart['Item'] = item_name;
cart['Quantity'] = quantity;
cart['Amount'] = amount;
cart['Total'] = total;
$.ajax({
url: 'https://www.google.com',
type: "POST",
//Datatype causes it to automatically become json and will expect json back
//return json back from php through json_encode($myArray);
dataType: "json",
data: cart,
success: function() {
alert('Message Sent');
}
});
in short: You used the wrong braces :)
I just changed it to an easier way of managing objects. The problem with your previous object was that it was built wrong. Should be something like:
var cart = {"Item":item_name,"Quantity": quantity,"Amount":amount,"Total":total};
I found a solution to my problem and I combined some your responses to find the answer.
$('#miniform').on('submit',function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var cart = {};
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = cart.amount * cart.quantity;
var jsonString = JSON.stringify(cart);
$.ajax({
url: url,
type: type,
data:{data:jsonString},
success: function(){
console.log('Email Sent');
},
error: function(error){
throw new Error('Did not work');
}
});
return false;
});
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.
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);
})
The MVC that creates the array of strings is
public JsonResult GetInvalidFilesAJAX(JQueryDataTableParamModel param)
{
string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" };
return Json(new
{
Status = "OK",
InvalidFiles = invalidFiles
});
}
And the javascript that should loop through and print out each string is
$.ajax(
{
type: 'POST',
url: 'http://localhost:7000/ManualProcess/GetInvalidFilesAJAX',
success: function (response) {
if (response.Status == 'OK') {
//Use template to populate dialog with text of Tasks to validate
var results = {
invalidFiles: response.InvalidFiles,
};
var template = "<b>Invalid Files:</b> {{#invalidFiles}} Filename: {{invalidFiles.value}} <br />{{/invalidFiles}}";
var html = Mustache.to_html(template, results);
$('#divDialogModalErrors').html('ERROR: The following files have been deleted:');
$('#divDialogModalErrorFiles').html(html);
How do I refer to the string in the array? The way above is not correct. All the example I find seem to be for when the Jason collection has property names.. in my case it is just a key value pair (I guess?)
There is no built in way. You must convert the JSON into an array or loop through the data yourself, e.g,
var data = JSON.parse(jsonString); // Assuming JSON.parse is available
var arr = [];
for (var i = 0, value; (value = data[i]); ++i) {
arr.push(value);
}
Alternatively:
var arr = [];
for (var prop in data){
if (data.hasOwnProperty(prop)){
arr.push({
'key' : prop,
'value' : data[prop]
});
}
}
And then to display it:
var template = "{{#arr}}<p>{{value}}</p>{{/arr}}";
var html = Mustache.to_html(template, {arr: arr});
This is assuming your JSON Object is one level deep.