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..
Related
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
I have an array of arrays of strings saved in a database column as a varchar:
[["ben"],["john","mike"],["ben"]]
I want to parse the data back into an array of arrays, so I can show the data on the screen. While attempting to do this, I ran into an awkward and annoying problem:
Here's the JSON response that is generated on the server and sent back to the client:
var response = "[{\"Names\":\""+ rows[i].Names + "\"}]";
res.send(response);
Here's the client code I wrote to parse the data:
jQuery.ajax({
type: "GET",
url: ...,
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).done(function(data) {
jQuery.each(JSON.parse(data), function(i, parsedData) {
var names = JSON.parse(parsedData.Names);
var labels = "";
for (var n = 0; n < names.length; n++) {
var label = "<label>" + names[n] + "</label>";
labels = labels + label;
}
console.log(labels);
});
});
This is the error i'm getting:
Here's the JSON validation:
How can I solve this?
There is a simple rule:
Never use string tools to create or modify JSON. No string concatenation (+), no string replace and God forbid no regex.
The only way to produce JSON is to use a JSON serializer on a data structure. And the only way to manipulate JSON is to parse it, modify the data structure, and then serialize it again. JSON itself is to be treated as a constant, for all intents and purposes.
Your server code violates that rule. Change it like this:
var responseData = [{
Names: rows[i].Names
}];
var response = JSON.stringify(responseData);
In the above, responseData is a data structure. You are free to modify it. response is derived from that. You are not free to modify it, the only thing you can do with response is to write it to the client.
Note that rows[i].Names might be JSON itself, so you end up with a double-encoded value in your response.
Provided the server sends the Content-Type: application/json header, the client can use this:
jQuery.get("...").done(function(data) {
// data is already parsed here, you don't need to parse it
jQuery.each(data, function(i, item) {
// item.Names is not yet (!) parsed here, so we need to parse it
var names = JSON.parse(item.Names);
var labels = names.map(function (name) {
return $("<label>", {text: name});
}
console.log( labels );
});
});
If you don't want to call JSON.parse() on the client, you have to call it on the server:
var responseData = [{
Names: JSON.parse(rows[i].Names)
}];
var response = JSON.stringify(responseData);
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 a loop that is generating a string
function jsonResponse(response)
{
var singleString = a + "," + b + "," + c + "|";
}
with console.log(singleString);
I see them all generated :
a1,b1,c1|
a2,b2,c2|
a3,b3,c3|
But how can I create a new variable allStrings that will concatenate all of these into one string? The loop is part of an ajax response that is looping through xml nodes to retrieve the data for those variables. I guess I need to make them part of an array and then join them back together for one big string?
To further clarify what I am trying to achieve is something like :
var allStrings = singleString[0] + singleString[1] + singleString[2] ;
a1,b1,c1|a2,b2,c2|a3,b3,c3|
To better explain the loop it looks like this :
$j.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function parseXml(data)
{
$j('.loader').fadeOut();
itemQueue = $j(data).find("ITEM").map( function ()
{
return {
date: $j("LAST_SCAN" , this).text(),
type : $j("PRODUCT_TYPE", this).text(),
cat : $j("CLASS_NAME", this).text(),
};
}).get();
getNextItem();
}
});
function getNextItem()
{
var item = itemQueue[0];
var singleString = item.date+ "," + item.type + "," + item.cat + "\n";
console.log( singleString );
$j.ajax({
url: s7query,
dataType: 'jsonp'
});
}
function s7jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
// run other processes when finished with checks
if (!itemQueue.length)
{
// alert ("ALL DONE");
}
}
You can use Array.join to convert an array to a string.
Example:
var arr = ['a1', 'b1', 'c1'];
console.log(arr.join(',')); // 'a1,b1,c1'
You can get rid if that loop and use:
array.join(',')
Where array is the array you want to turn in to a string separated by commas.
To join the strings together you just need to construct a string concatenation:
allStrings.concat(string1, string2, ..., stringX)
It sounds like you're making separate XHRs for independent XML nodes, in which case you may want to reconsider your approach. If possible, I would iterate over the XML nodes in their entirety and gather all necessary request data. Then you can make a single XHR (cutting down on HTTP connections, which is good!) and get a single response that could contain the entirety of the response (i.e. allStrings). It should be easier on your server and make a noticable difference on the client side in pretty much all situations.