Display org.json.JSONArray object in Dojo Grid - javascript

I wrote a servlet to fetch data from server, adding it to JSONObject and returning that JSONObject to Dojo request.get() function. I am receiving the data successfully but don't know how to display that json.
Here is my request.get() function:
request.get("FilenetDojoServlet", {
sync: true,
timeout: 3000,
handleAs: "json"
}).then(function(data){
data4 = json.stringify(data);
console.log("Data from server : "+data4); //displaying json string of data.
console.log("List from data : "+data4.osList); //should display "osList" contained within data
});
And this is what I am getting in console:
Data from server : {"map":{"osList":{"myArrayList":["UDMS","EBILLING","BATELCO"]}}}
List from data : undefined
How can I fetch values from myArrayList in json string?
I tried like this:
var data4 = data.map.osList.myArrayList
but failed!
This is the stringified JSON data:
{"map":{"osList":{"myArrayList":["UDMS","EBILLING","BATELCO"]}}}

You need to use JSON.parse() to convert a JSON string into an object. At the moment if you try typeof data4 it should return "string", but you want an object.
Dojo automatically decodes JSON for you. (There appears to have been confusion about what the OP wanted.)

Related

Extract JSON response from jquery ajax to html div

I could not retrieve data to jquery div element but i can see ajax response in firebug.
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})
this is my response.for example my url contains data productCount:64 ,I should extract productCount from ajax success and display it in html div id result
When you parse out the JSOn data you use it like so:
var parsed_data = JSON.parse(JSON_DATA);
$('#result').html(parsed_data.key);
So if your parsed_data is somewhat like:
{name:"test",age:12}
then you use it like:
$('#result').html(parsed_data.name); //it will give you test
if you really want to print out the whole data use JSON.stringify(obj) like so:
$('#result').html(JSON.stringify(parsed_data));
In your code you are returning a json and you are trying to insert ino the div it, into the div you can only insert html code instead json.
Try to inspect the json you are returning and in case you need to insert each element into the div, do it, but don't do for all.
The html() method doesn't know what you want to assign, it only insert an html.
You need to iterate over your json data in returnData. You are not able to put json directy into html. You need to convert / parse / iterate it before. So, for example:
$.each(returnedData, function (index, value) {
// do stuff with it, e. g.:
// $('#result').html($('#result').html() + value);
});
https://jsfiddle.net/m8udusps/
The code here actually works. However it says there is a problem when it is parsing the JSON. You needed to add crossDomain: true, to allow it to actually get the results.
Having received a supposed JSON struct like:
{
"Field1": "value1",
"Field2": "value2"
}
This code gets the values of the keys (just first key in this example). Result is an alert message with Data: value1:
$.ajax({
'url' : './localurl',
'type' : 'GET',
'success' : function(data) {
alert("Data: "+data.Field1);
},
'error' : function(request,error) {
alert("Error in response: "+JSON.stringify(data));
}
});
In this case Field1 is the key received and it is directly accesible through data variable, so it is not necessary to do the JSON.parse(data) (in fact this JSON.parse produce an error)

why use JSON.Parse(data) after ajax sucess?

I have this following code.
success: function(data) {
console.log(data) //everything
console.log(data['quote']); //undefined
var JSONObject = JSON.parse(data); //why parse again?
var quote =JSONObject['quote']
console.log(data['quote']); //returns quote
}
why do I need to parse the JSON object again even though the return from api call is already a JSON Object?
It seems the data returned from server is JSON string instead JSON object. If the data is string, you need to parse that string to javascript object.

Jquery post loop through json data

I'm trying to loop through my data I received when doing a jquery .post however it's showing up as a much higher count than it is. What is making it say 109 as the length of data?
.done(function( data ) {
console.log(data);
console.log(data.length);
});
Below is the console logs:
[{"lat":33.115868,"lng":-117.186295},{"lat":33.117237,"lng":-117.186295},{"lat":33.111866,"lng":-117.186295}]
109
Although, it looks like JSON, the data received from server is string. To convert it into JSON use JSON.parse before iterating over it.
Use
JSON.parse(data);
to get JSON object from the string.
OR use dataType: 'json' in ajax configuration.
you need to parse the encoded data using:JSON.parse or $.parseJSON.
var ndata=JSON.parse(data);
console.log(ndata.length);

Parsing JSON returned via an AJAX POST formating issue

I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.

passing json array ajax

Trying to pass a array using ajax call.
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info: info, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
However when i try to catch it on the server side using :
request.getParameter("info"); //Displays null**
Also, if i wish to send an array of arrays ? is it possible?
I tried using serialize however my IE throws error that serialize : object doesnt support this property i Did include jquery lib.
You can use JSON.stringify(info) to create a JSON representation of the object/array (including an array of arrays). On the server side you should be able to get the string via getParameter and then unserialize it from JSON to create constructs JSP can use.
Yes,It is Possible to send arrays.
var info_to_send = ['hi','hello'];
$.ajax({
type: "POST",
data: {info: info_to_send, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
You can only provide strings in a request url.
You could encode the array like so:
info = JSON.stringify(info);
// results in "['hi', 'hello']"
Then send it to the server, also JSON parse on the server.
You will need to go to http://www.json.org/ to get a Java implementation of JSON parsing.

Categories

Resources