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
Related
This is what I'm doing:
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors = data;
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
This is the error:
Uncaught TypeError: supervisors.replace is not a function
If I do this:
$('#divSupervisorList').text(data);
The the result on screen is this:
John Foo, Jane Bar
What I want is:
John Foo
Jane Bar
But I'm having trouble replacing the , with a <br />. At first I tried:
$('#divSupervisorList').text(data.replace(",", "<br />"));
And when that didn't work, I went to using a string that is declared before the ajax call. I also tried using .split() but got the same error.
Not sure what I'm doing wrong.
UPDATE:
As many have pointed out, my return data is not a string, but an object:
(4) ["Adam Brown", "Karl Walser", "Jeremy Smith", "Nathan Graham"]
0 : "Adam Brown"
1 : "Karl Walser"
2 : "Jeremy Smith"
3 : "Nathan Graham"
So, now I gotta figure out how to split this array into a string :-)
My guess is that the data param is actually an array, not a string, and you're seeing it with commas only because JS is sneakily stringifying it that way. You could combine them in a string using the join method for arrays:
supervisors.join('<br />')
However, if you try to use "<br />" in jQuery's text function, it will get escaped. You can use the html function instead. So,
$('#divSupervisorList').html(supervisors.join('<br />'));
The data you are having in response is a Json and not a string.
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors =JSON.stringify( data);
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
Read more:. [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify].
To replace commas inside each member of your array, you need to map .replace() on the array values:
let result = data.map(function(o){return o.replace(',','<br />')});
To join the members of the array, separating them with a <br />, you need .join():
let result = data.join('<br />');
Note there are no actual commas separating the array members, that's just a conventional way of displaying array values so humans can read and understand them, but there's nothing to replace. All you need to do is join the members with the separator of your choice (<br />) which, by default, is a comma.
So this would also give you the same result:
let result = data.join().replace(',','<br />');
... because .join() would glue the strings using , and .replace() would replace them with <br />s.
According to the jQuery docs:
[dataType is] "json": Evaluates the response as JSON and returns a JavaScript object
So your data is actually an object. You need to access the relevant string property, e.g. data.supervisors.replace(...) - depending on your object model.
I recommend adding a console.log(data) call to your success callback and checking the developer console in your browser by pressing F12 to investigate the source of your issue.
Update: The output of above call to console.log hints at data being an array. Thus, you need to replace
$('#divSupervisorList').text(data.replace(",", "<br />"));
with
$('#divSupervisorList').html(data.join("<br />"));
I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");
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 + '¶m_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.
I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.
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..