My tomcat log is only showing one item being passed in..
var itemArr = ["someItem", "someItem2", "someItem3"];
$.ajax({
type: "POST",
url: "myServlet",
data: $.param({item: itemArr})
});
The array contains around 20 elements.
Also if i do:
var params = $.param({item: itemArr});
alert(params);
All the values come out formatted as item=someitem&item=someitem2..etc etc
But the ajax post only outputs the first item from the array. I want them all passed through to the server in the request.
Any help would be much appreciated.
EDIT:
Using version 1.3.2 also tried with 1.4.4 - same problem
I think your $.param() call should just be this:
var itemArr = ["someItem", "someItem2", "someItem3"];
$.ajax({
type: "POST",
url: "myServlet",
data: $.param(itemArr)
});
EDIT: Nick is onto something there...
From the jQuery.param() documentation:
// <=1.3.2:
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4:
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
EDIT AGAIN
Maybe something like this will work for you, to emulate the 1.4 behavior:
var itemArr = ["someItem", "someItem2", "someItem3"];
var paramed = decodeURIComponent($.param({ 'item[]': itemArr }));
Demo here: http://jsfiddle.net/Ender/EHd78/1/
Oh right I missed the first sentence, yes you will only get one item passed to your server it should be an array.
This from firebug when I make that request,
item[] someItem
item[] someItem2
item[] someItem3
Related
I want to receive the value thought iterator, when I use
$('#someModal').find('input[name=nameProBangHHModal]').val(data[0].TenNhanQuyCach);
it works as expected.
But when I use an iterator, the return shows [object Object].TenNhanQuyCach - not the data returned.
I try to search for other topic but I'm stuck on this. How to get the data returned in array[data[0]] with the value from the iterator method?
Thank you for your time!
$.ajax({
url: 'someurl to retrive data',
type: 'POST',
data: {id:id},
success: function(data,status) {
var tenCot = ['nameProBangHHModal','valueBangHHModal',];
var tenCotTrongCsdl = ['TenNhanQuyCach','DonViTinh',];
console.log(tenCotTrongCsdl[0]);
for (i=0;i <= tenCot.length - 1;i++) {
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0]+'.'+tenCotTrongCsdl[i]');
}
oh i find out the answer after search topic for array: this one: How can I access and process nested objects, arrays or JSON?.
and find out that need to use [] for variable, not the ".".
this one work for me:
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0][tenCotTrongCsdl[i]]);
I'm having trouble sending the form via ajax. In addition to the fields populated by the user, I need to send an array of objects together.
AJAX POST:
submitHandler: function (form) {
$.ajax({
url: urlPost,
type: "POST",
dataType: "json",
data: $(form).serialize() + JSON.stringify(myArray),
success: function (resposta) {
alert('success');
}
});
}
If I send only $(form).serialize() I can, but with the array not.
ARRAY:
myArray = [{name: 'a', node: 1}, {name: 'b', node: 12}, ...];
Change your data: $(form).serialize() + JSON.stringify(myArray) to data: $(form).serialize() + "&arr=" + JSON.stringify(myArray). For Further help refer to https://stackoverflow.com/a/10398820/4518930
.serialize() + Some JSON String doesn't make sense.
According to the docs:
https://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded
notation.
So you're really taking a string like foo=bar&goat=baz and then adding a JSON string to like. Which makes no sense.
I think you'd be better off serializing the form yourself into a JSON object. Adding another key for your array and then dumping that object to JSON via JSON.stringify and that string is your request data.
After the tip of Cody Caughlan, I created an object that adds all the properties of the form and the array itself. The code looks like this:
var dataForm = {};
$($(form).serializeArray()).each(function(index, obj){
dataForm[obj.name] = obj.value;
});
dataForm["MyArray"] = myArray;
And ajax: post: dataForm.
I'm trying to send object array to node.
If i'm sending it without stringify, i'm getting an array with the same length that i sent, but empty (["", ""]);
if i send it with JSON.stringify , this it the result:
{'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1","newShelf":"","actionType":"in","whareHouse":"Main"},{"itemNumber":"13544","currentShelf":"1B1","amount":"1","newShelf":"","actionType":"in", "whareHouse":"Main"}]': '' }
This is how i'm sending it:
for (var i=1; i<=m; i++){
itemIdTemp= document.getElementById("itemIdShell"+i).value;
shellTemp= document.getElementById("id_shell"+i).value.toUpperCase();
newShellTemp= document.getElementById("id_shell_new"+i).value.toUpperCase();
shellAmountTemp = document.getElementById("amountShell"+i).value;
itemAmount=0;
let itemData={
itemNumber:itemIdTemp,
currentShelf:shellTemp,
amount:shellAmountTemp,
newShell:newShellTemp,
actionType:direction,
whareHouse:"Main",
};
console.log(itemData);
itemsObject.push(itemData);
}
console.log(itemsObject);
$.post('/itemShell/updateMulti',
JSON.stringify(itemsObject),
function(data){
console.log(data);
});
The object contain a string of the array and i can't get it.
I tried Json.Parse(), it won't work in this case.
any suggestions?
Have a look at this example code
const jsObjectArray = [
{name: "Homer", age:56 },
{name: "Marge", age:50 },
];
const buf = JSON.stringify(jsObjectArray);
console.log("Stringified object: "+buf);
//
// Now convert it back to an object
//
const newObject = JSON.parse(buf);
console.log("Reconstituted object: "+newObject);
It's in this codepen too:
https://codepen.io/mikkel/pen/KRayye
I found the problem.
It must be declare as JSON type when post to Node, so u need to use ajax:
$.ajax({
url: '/itemShell/updateMulti',
type:"POST",
data:JSON.stringify(dataTosend),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){}
}
and i also change it to object type like this:
dataToSend={dataArr:itemsObject}
So in node it's appearing as array
My Guy work a little bit on the string before sending it
First get the string the stringify is returning
var json_string = JSON.stringify(itemsObject);
var string = json_string.replace("'", "\'");
string = '{\'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1",
"newShelf":"","actionType":"in","whareHouse":"Main"},
{"itemNumber":"13544","currentShelf":"1B1","amount":"1",
"newShelf":"","actionType":"in", "whareHouse":"Main"}]\': \'\' }';
first_str = string.split("': "); // remove the last useless chars
second = first_str[0].substring(2, first_str[0].length); // remove the first two chars
$.post('/itemShell/updateMulti', second,
function(data){
console.log(data);
});
the second should have the correct string.
GOODLUCK
$.ajax({
type: 'POST',
url: 'url',
data: val,
async: false,
dataType: 'json',
success: function (max) {
console.log(max.origin);
}
});
Then i am getting an output which is
["test,origin"]
I want to split it like .
test
origin
Please suggest me .
Much appreciated
If your returned value of max.origin really is ["test,origin"], you have to do something like this
var data = max.origin[0].split(',');
so that data will contain a list of the elements that are comma-separated. However, if your max.origin is in the form of ["test", "origin"], you can simply select each/all items by going through a for-loop and (optionally) print them out:
for (var i = 0; i <= max.origin.length; i++) {
console.log(max.origin[i]);
}
If you know that you only get the two elements (test and origin) each time, #void's answer is a good approach.
max.origin[0].split(",")[0] will give you test
max.origin[0].split(",")[1] will give you origin
I'm trying to GET some data from a site using jQuery $.get. I need to set 2 parameters of the same type:
..&q=Some Text&q=Some other text
jQuery appears to be overwriting the first instance of q with the second and only sending 1. Any way around this?
This is the code I was trying to use:
var params = {
"otherParam":"x",
"q":text,
"q":title
};
$.get(url, params, mySuccessFunction);
Try:
var params = {
"otherParam": "x",
"q": [ text, title ]
};
edit — more information: array-valued parameters like that are treated specially by jQuery. To appease many common server frameworks, by default (since release 1.5 or 1.6 I think) those will result in parameter names that include "[]" (open- and close-bracket characters) as a suffix (no number, contrary to my erroneous comment below). If you don't want that, you can set
jQuery.ajaxSettings.traditional = true;
and it'll just be "q" instead of "q[]".
And another way to solve it that does not require encodeURIComponent() or messing with jQuery.ajaxSettings.traditional = true; which I would prefer not to do because I don't want to interfere (even temporarily) with what other parts of the site might be doing simultaneously.
Is:
var params=[
{name:"q", value:title},
{name:"q", value:text}
];
$.get(url, params, mySuccessFunction);
Another approach without modifying jQuery.ajaxSettings.traditional = true; is to use $.param() http://api.jquery.com/jQuery.param/
So something like this:
var params = {
"otherParam": "x",
"q": [ text, title ]
};
$.get(url, $.param(params, true), mySuccessFunction);
You can write the URL like this :
$.get(
url+'?q='+encodeURIComponent(text)+'&q='+encodeURIComponent(title)+'&otherParam='+encodeURIComponent('x'),
mySuccessFunction
);
Things are pretty simple and described in jQuery website http://api.jquery.com/jquery.param/.
First create a params object
var params=[{
name: 'param1',
value: 'hello'
},
{
name: 'param1',
value: 'alex'
}];
next create the data to be sent to the service.
var data = jQuery.param(params);
That object can be inserted as the data param of the ajax request. I like using a settings object
var settings={
url: 'api/domain/timeline',
type: 'get',
contentType: 'application/json',
data: data
};
$.ajax(settings);