Post data $(form).serialize() and an array together - javascript

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.

Related

How to pass the data as object in jquery ajax

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]]);

Send object array to node/Parse to Json

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

how to retrieve array in hidden field

I am storing my array in hidden field
var myarray = [];
if ($(this).prop('checked')) {
myarray.push(val);
$('#myhidden').val(JSON.stringify(myarray));
}
how can I retrieve that array ? because I want that array to past it to other page using jquery.ajax
I tried this
var retarray = $('#myhidden').val();
["110","118"]
when I send that using jquery.ajax
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: 'param1=' + param1 + '&param_array=' + retarray,
success: function(data) {
}
});
it gives me error because it is not an array.
Thank you in advance.
You're converting your array to a string here:
$('#myhidden').val(JSON.stringify(myarray));
If you need it to be an array, then you need to parse this array back from the string
var retarray = JSON.parse($('#myhidden').val());
for example:
var array = [1,2,3,4]; // create an array
var stringarray = JSON.stringify(array); // convert array to string
var array2 = JSON.parse(stringarray); // convert string to array
Try this
var retarray = encodeURIComponent($('#myhidden').val());
Your ajax request is is using the method POST and you have specified a data type of json which means your http request is sending json in the body.
So you can send your whole request message as json, like this:
// get json from input
var retarray = $('#myhidden').val();
// parse json into js
var arr = JSON.parse(retarray);
// create your request data
var data = { param1: param1, param_array: arr };
// stringify
var json = JSON.stringify(data);
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: json, // the json we created above
success: function(data) {
}
});
Then in your php script you can deserialize the json message to a php object like so:
$json = file_get_contents('php://input'); $obj = json_decode($json)
You can do this :
$('#myhidden').val(myarray.split("|")); //set "0|1".split("|") - creates array like [0,1]
myarray = $('#myhidden').val().join("|"); //get [0,1].join("|") - creates string like "0|1"
"|" is a symbol that is not present in array, it is important.

Create array of arrays from JSON

I am receiving after an ajax call the following as response using in php json_encode:
"['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]", "['2013-02-27', 6]", "['2013-02-28', 6]", "['2013-03-01', 3]", ...
How can I make in JavaScript from this an array of arrays? Is this even possible? I mean, I've tried with jQuery makeArray or with parseJSON with no success. What is the most preferred method?
Edit:
function submitForm(t) {
$.ajax({type:'GET', url: 'charts.php', data:$(page_id).serialize(), success:
function(response) {
var myFanRemovesData = new Array(response);
var myChart = new JSChart(chart_id, 'line');
myChart.setDataArray(myFanRemovesData);
I have to use the array of arrays to set myFanRemovesData with it
1) strip out the double-quotes ("):
var json = json.replace(/"/g, '');
2) wrap the whole thing in square brackets:
json = "[" + json + "]";
3) replace the single-quotes with double-quotes (because the singles won't parse):
json = json.replace(/'/g, '"');
4) parse the json string:
var arrays = JSON.parse(json);
Here is a working example. It will alert the first date in the first array. (note: the data is pulled from the DIV to simulate the AJAX call and to avoid me having to mess around with escaping quote characters)
Try:
var response = ["['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]"];
for (var i = 0; i < response.length; i++) {
var cleaned = response[i].replace(/'/g, "\"");
response[i] = $.parseJSON(cleaned);
}
DEMO: http://jsfiddle.net/hu3Eu/
After this code, the response array will contain arrays, made out of the original strings.
Just example.. because you haven't provide us with any code...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
dataType: 'json',
}).done(function( responde ) {
$.each(responde, function(i, v){
alert(v.0 + ' --- ' + v.1);
});
});
If you receive and expecting json you directly can use it as array/object :)
If its array you have to make a each loop so you can access each value..

jQuery $.ajax method only sends one item from my serialized array

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

Categories