access javascript object in servlet [duplicate] - javascript

I am creating and sending a JSON Object with jQuery, but I cannot figure out how to parse it properly in my Ajax servlet using the org.json.simple library.
My jQuery code is as follows :
var JSONRooms = {"rooms":[]};
$('div#rooms span.group-item').each(function(index) {
var $substr = $(this).text().split('(');
var $name = $substr[0];
var $capacity = $substr[1].split(')')[0];
JSONRooms.rooms.push({"name":$name,"capacity":$capacity});
});
$.ajax({
type: "POST",
url: "ParseSecondWizardAsync",
data: JSONRooms,
success: function() {
alert("entered success function");
window.location = "ctt-wizard-3.jsp";
}
});
In the servlet, when I use request.getParameterNames() and print it out to my console I get as parameter names rooms[0][key] etcetera, but I cannot parse the JSON Array rooms in any way. I have tried parsing the object returned by request.getParameter("rooms") or the .getParameterValues("rooms") variant, but they both return a null value.
Is there something wrong with the way I'm formatting the JSON data in jQuery or is there a way to parse the JSON in the servlet that I'm missing?
Ask for more code, even though the servlet is still pretty much empty since I cannot figure out how to parse the data.

The data argument of $.ajax() takes a JS object representing the request parameter map. So any JS object which you feed to it will be converted to request parameters. Since you're passing the JS object plain vanilla to it, it's treated as a request parameter map. You need to access the individual parameters by exactly their request parameter name representation instead.
String name1 = request.getParameter("rooms[0][name]");
String capacity1 = request.getParameter("rooms[0][capacity]");
String name2 = request.getParameter("rooms[1][name]");
String capacity2 = request.getParameter("rooms[1][capacity]");
// ...
You can find them all by HttpServletRequest#getParameterMap() method:
Map<String, String[]> params = request.getParameterMap();
// ...
You can even dynamically collect all params as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("rooms[" + i + "][name]");
if (name == null) break;
String capacity = request.getParameter("rooms[" + i + "][capacity]");
// ...
}
If your intent is to pass it as a real JSON object so that you can use a JSON parser to break it further down into properties, then you have to convert it to a String before sending using JS/jQuery and specify the data argument as follows:
data: { "rooms": roomsAsString }
This way it's available as a JSON string by request.getParameter("rooms") which you can in turn parse using an arbitrary JSON API.
Unrelated to the concrete problem, don't use $ variable prefix in jQuery for non-jQuery objects. This makes your code more confusing to JS/jQuery experts. Use it only for real jQuery objects, not for plain vanilla strings or primitives.
var $foo = "foo"; // Don't do that. Use var foo instead.
var $foo = $("someselector"); // Okay.

Related

Get jqGrid ajax Nested Array of Json string in C# by Newtonsoft Json

I'm trying to parse Json string and collect array values present inside it.
{"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\"Emp_ID\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Name\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Designation\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"City\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"State\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Country\",\"op\":\"cn\",\"data\":\"ASAS\"}]}"}
PS: Above string is coming from jqGrid Ajax to the WebMethod in C#.
I'm not getting success on getting filters->rules[0]->data
What I've tried :
dynamic jObj = JObject.Parse(postData);
var data = jObj.filters.rules[0].data;
getting error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
dynamic jObj = JObject.Parse(postData);
var filters = jObj.filters; //Sucess: getting filters here
var rules1 = filters["rules"]; //Error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
var rules2 = filters.rules; //Error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
How to get value inside filters->rules AND filters->rules[0]->data ?
You must parse the internal object like this :
var obj = "{\"_search\":true,\"nd\":1492064211841,\"rows\":30,\"page\":1,\"sidx\":\"\",\"sord\":\"asc\",\"filters\":\"{\\\"groupOp\\\":\\\"OR\\\",\\\"rules\\\":[{\\\"field\\\":\\\"Emp_ID\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Name\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Designation\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"City\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"State\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Country\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"}]}\"}";
dynamic jObj = JObject.Parse(obj);
var data = JObject.Parse(jObj.filters.Value);
var test = data.rules;
Console.WriteLine(data);
Console.ReadLine();
I don't have the knowledge about C# but I have tried into it on JavaScript
In your json, in filters field not is'nt proper json it is string
I have do this on javascript might it will help's you
var a = {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\"Emp_ID\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Name\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Designation\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"City\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"State\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Country\",\"op\":\"cn\",\"data\":\"ASAS\"}]}"}
console.log(a.filters)
it is returns
"{"groupOp":"OR","rules":[{"field":"Emp_ID","op":"cn","data":"ASAS"},{"field":"Name","op":"cn","data":"ASAS"},{"field":"Designation","op":"cn","data":"ASAS"}
and it is string now i'm again parse into it on JSON
b = JSON.parse(a.filters)
console.log(b.rules)
now it returns rules objects

Cannot retrieve data from javascript json object created in javascript

I have a servlet where it returns a string like [["one","two"],["one","two"]], which is an array representation.
This was sent to the front end using the Gson library's toJson() method as a String. It sends this String array along with some other attributes in JSON format and then I'm using the toJson() method to send it to front end.
In the Ajax response handling, I'm doing a $.parseJSON() on the object and retrieving the values. (It works fine and I was able to retrieve that array string.)
Now in JavaScript I need to create another JSON object with some other values along with this string array and send it to another JavaScript method. But in that method I cannot retrieve the values. My motive is to extract this array string as an array and iterate it.
Following is what I do in JavaScript to send to JavaScript method:
var streamId = stream + CONSTANTS.colon + streamVersion;
var eventsData = {};
var jsonData = [];
eventsData ["source"] = streamId;
eventsData ["data"] = eventsArray;
jsonData.push(eventsData);
onSuccessFunction(jsonData);
In onSuccessFunction I tried to get jsonData.data, but it says undefined.
Any suggestions?

Javascript: Parse JSON output result

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

javascript array mistake

I used to create an array in js
var data = new Array();
data['id'] = self.iframeFields.id.val();
data['name'] = self.iframeFields.name.val();
data['location'] = self.iframeFields.location.val();
data['about'] = self.iframeFields.about.val();
data['company'] = self.iframeFields.company.val();
data['website'] = self.iframeFields.website.val();
but passing var data returns null value
but data['id'] return value.
What did I do wrong?
EDIT:
After nrabinowitz's answer, i was using
if ($.isArray( data )){
ajax({
url: myurl,
data: {
method: "updateProfile",
data: data
},
normalizeJSON: true,
success: function( response ){
// Check to see if the request was successful.
if (response.success){
alert(response);
} else if (onError){
// The call was not successful - call the error function.
alert(response);
}
}
});
}
as it is an object not an array,
it was not returning nothing,
Removing
if ($.isArray( data )){
}
solves the issue.
In Javascript, you want an object, not an array:
var data = {};
data['id'] = self.iframeFields.id.val();
// etc...
You're expecting the array to work like an associative array in PHP, but Javascript arrays don't work that way. I'm assuming you're setting these values by key, and then trying to iterate through the array with something like a for loop - but while you can set values by key, because in Javascript an array is just another object, these values won't be available in standard array iteration, and the length of the array will still be 0.
EDIT: You note that you're using jQuery's .ajax() function to post the data to the server. The .ajax() method expects an object containing key/value pairs, and sends them to the server as a GET or POST parameters. So in your case, if you're using an object as I describe above, your server will receive the parameters "id", "name", etc in the $_POST array - not a "data" parameter.
I suspect, though I haven't tested this, that using var data = new Array(); wouldn't work at all, because of the way jQuery serializes the data passed to .ajax() - even though an array is also an object, jQuery checks if it's an array and treats it differently:
If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()
[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]
So it wouldn't use the key/value pairs you set at all - you would be passing an empty array and no parameters would be passed to the server.
So the right approach here:
Use var data = {};
On the server, look for $_POST['id'], $_POST['name'], etc.
You're using the array like a regular object. You're augmenting the array with additional properties, but the array itself is still empty (you should have an array.length === 0, hence the null). Try changing
var data = new Array();
to
var data = {};
and see what you get.

New to JSON, what can I do with this json response

A website returns the following JSON response, how would I consume it (in javascript)?
[{"ID1":9996,"ID2":22}]
Is JSON simply returning an array?
We use:
function evalResponse(response) {
var xyz123 = null;
eval("xyz123 = " + response);
return xyz123;
}
An alternative method is to simply use:
var myObj = eval(response);
Basically, you have to call eval() on the response to create a javascript object. This is because the response itself is just a string when you get it back from your AJAX call. After you eval it, you have an object that you can manipulate.
function myCallback(response) {
var myObj = evalResponse(response);
alert(myObj.ID1);
}
You could use a javascript library to handle this for you. Or, you could try to parse the string yourself. eval() has it's own problems, but it works.
If you use http://www.JSON.org/json2.js you can use it's method JSON.parse to retrieve the json string as an object (without the use of eval (which is considered evil)), so in this case you would use:
var nwObj = JSON.parse('[{"ID1":9996,"ID2":22}]');
alert(nwObj.ID1); //=> 9996
It looks like an array with a single object holding two properties. I'd much prefer to see the same data structured like this:
{"ID":[9996,22]}
Then you have a single object holding an array with two elements, which seems to be a better fit for the data presented. Then using Endangered's evalResponse() code you could use it like this:
var responseObj = evalResponse(response);
// responseObj.ID[0] would be 9996, responseObj.ID[1] would be 22
I think the other answers might not answer your question, maybe you're looking for a way to use that "array of 1 object". Maybe this can help:
var arr = [{"ID1":9996,"ID2":22}];
var obj = arr[0];
var id1 = obj.ID1;
var id2 = obj.ID2;
Here's how you get to your data:
<script type="text/javascript" >
var something = [{"ID1":9996,"ID2":22}]
alert(something[0].ID1)
</script>
The JSON you posted represents an array containing one object, which has attributes ID1 and ID2 (initialized to the respective values after the colon).
To convert the string to a javascript object, pass it to eval, like this:
var obj = eval('[{"ID1":9996,"ID2":22}]');
However, this method will fail if you only have a single object instead of an array, so it is safer to wrap it in parenthesis:
var obj = eval('(' + jsonResponse + ')');

Categories

Resources