Displaying JSON data in Javascript loop - javascript

I am having an issue displaying json data. I have searched and found many examples, but for some reason I get the "Cannot read property 'length' of undefined" error, because "var object = notes.data;" comes back as undefined.
Why is object undefined? From everything I can see I am doing it right.
My json that is returned.
{
"data":[
{
"NumberOfAnswers":25,
"Answer":"51-89 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":54.35
},
{
"NumberOfAnswers":21,
"Answer":"90-100 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":45.65
}
]
}
And here is the function to display it. (With some debugging code as well)
function format(notes) {
console.log(notes); //this displays the json
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
Here is the ajax function:
$.ajax({
type: 'post',
url: '/rmsicorp/clientsite/pacingModal/surveyajax2.php',
success: function(result) {
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
detailsrows.splice(RowID, 1);
} else {
row.child(format(result)).show();
tr.addClass('shown');
if (RowID === -1) {
detailsrows.push(tr.attr('id'));
}
}
}
});

Most likely, the response is still in string format. You can add JSON.parse to convert it to an object and then be able too access the data property.
Try modifying your function like this to see if it fixes the problem.
function format(notes) {
console.log(notes); //this displays the json
// The following converts the response to a javascript object
// and catches the exception if the response is not valid JSON
try {
notes = JSON.parse(notes);
} catch(e) {
console.log('notes is not valid JSON: ' + e);
}
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}

Related

Using Cookies to transfer JSON data between 2 web pages

So I've been trying to do this for more than a day now. I'm getting a few user inputs through a form (ex - a name of a car), then I search through a JSON file to see whether its available. After this I'm trying to send the results of the search to a results page. I've been trying to use a cookie for this process. However there is a problem that I can't figure out. Following is my code,
This is getting input and searching:
function search() {
var name = $("input[name=carName]").val();
var cars = new Array();
$.getJSON("properties.json", function (data) {
$(data.cars).each(function (index, value) {
if (value.name == name) {
cars.push(value);
}
});
if (cars.length > 0) {
send(cars);
} else {
// do some handling
}
});
function send(cars) {
var str = JSON.stringify(cars);
Cookies.set("carResults", str);
window.location.replace("result.html");
}
This is the script from result.html
<script>
$(document).ready(function () {
var temp = Cookies.get("carResults");
var cars = JSON.parse(temp);
if(results!=null) {
for (var i = 0; i < results.length; i++) {
var temp1 = "Found a " + cars[i].name;
$("#resultArea").append(temp1);
}
} else {
$("#resultArea").append("Nothing to show");
}
});
</script>
PS. I'm using a javascript library called cookie.js for creating cookies

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

Parsing JSON array of objects: undefined property

So, similar to my my previous question here (I was unsure whether to make a new question or edit the old one), I managed to sucessfully parse the body JSON response using the code seen below.
However when attempting to do the same to the event_calendar_date, I get this: Failed with: TypeError: Cannot read property 'und' of undefined. I would have assumed that to get to the next object in the array the method would be the same for both, however that does not appear to be the case.
JSON response from the server:
[
{
"revision_uid":"1",
"body":{
"und":[
{
"value":"Blah Blah.",
"summary":"",
"format":null,
"safe_value":"Blah Blah.",
"safe_summary":""
}
]
},
"event_calendar_date":{
"und":[
{
"value":"2015-07-20 14:00:00",
"value2":"2015-07-20 20:00:00",
"timezone":"America/New_York",
"timezone_db":"America/New_York",
"date_type":"datetime"
}
]
}
}
]
My Code:
Parse.Cloud.httpRequest({
method: "GET",
url: 'http://www.scolago.com/001/articles/views/articles',
success: function(httpResponse) {
var data = JSON.parse(httpResponse.text);
var articles = new Array();
for (var i = 0; i < data.length; i++) {
var Articles = Parse.Object.extend("Articles"),
article = new Articles(),
content = data[i];
article.set("body", content.body.und[0].value);
article.set("vid", content.vid);
article.set("title", content.title);
article.set("events", content.event_calendar_date.und[0].value);
articles.push(article);
};
// function save(articles);
Parse.Object.saveAll(articles, {
success: function(objs) {
promise.resolve();
},
error: function(error) {
console.log(error);
promise.reject(error.message);
}
});
},
error: function(error) {
console.log(error);
promise.reject(error.message);
}
});
I am afraid you didn't give us all code, or you are using not the code you posted in this question, because it should run fine, as you can see in this demo:
for (var i = 0; i < data.length; i++) {
var content = data[i];
console.log(content.event_calendar_date.und[0].value);
};
EDIT and solution
As I expected, JSON you are getting doesn't have field event_calendar_date for 2nd, and 3rd object. I checked in your full code on GitHub.
First object has correct event_calendar_date field, but next records don't have. See how is JSON you are getting formatted - http://www.jsoneditoronline.org/?id=b46878adcffe92f53f689978873a3474.
You need to check first if content.event_calendar_date is present in record in your current loop iteration or add event_calendar_date to ALL records in JSON response.

Office.context.document.getFileAsync throwing errors

I am getting a very strange issue whereby when I try to extract the word document as a compressed file for processing in my MS Word Task Pane MVC app the third time, it will blow up.
Here is the code:
Office.context.document.getFileAsync(Office.FileType.Compressed, function (result) {
if (result.status == "succeeded") {
var file = result.value;
file.getSliceAsync(0, function (resultSlice) {
//DO SOMETHING
});
} else {
//TODO: Service fault handling?
}
});
The error code that comes up is 5001. I am not sure how to fix this.
Please let me know if you have any thoughts on this.
Additional Details:
From MSDN:
No more than two documents are allowed to be in memory; otherwise the
getFileAsync operation will fail. Use the File.closeAsync method to
close the file when you are finished working with it.
Make sure you call File.closeAsync before you read the file again - that could explain the issue you are seeing.
More at: https://msdn.microsoft.com/en-us/library/office/jj715284.aspx
I have an example about how to use this API correctly. Actually the current example in the MSDN is not very correct. This code is tested in Word.
// Usually we encode the data in base64 format before sending it to server.
function encodeBase64(docData) {
var s = "";
for (var i = 0; i < docData.length; i++)
s += String.fromCharCode(docData[i]);
return window.btoa(s);
}
// Call getFileAsync() to start the retrieving file process.
function getFileAsyncInternal() {
Office.context.document.getFileAsync("compressed", { sliceSize: 10240 }, function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
document.getElementById("log").textContent = JSON.stringify(asyncResult);
}
else {
getAllSlices(asyncResult.value);
}
});
}
// Get all the slices of file from the host after "getFileAsync" is done.
function getAllSlices(file) {
var sliceCount = file.sliceCount;
var sliceIndex = 0;
var docdata = [];
var getSlice = function () {
file.getSliceAsync(sliceIndex, function (asyncResult) {
if (asyncResult.status == "succeeded") {
docdata = docdata.concat(asyncResult.value.data);
sliceIndex++;
if (sliceIndex == sliceCount) {
file.closeAsync();
onGetAllSlicesSucceeded(docdata);
}
else {
getSlice();
}
}
else {
file.closeAsync();
document.getElementById("log").textContent = JSON.stringify(asyncResult);
}
});
};
getSlice();
}
// Upload the docx file to server after obtaining all the bits from host.
function onGetAllSlicesSucceeded(docxData) {
$.ajax({
type: "POST",
url: "Handler.ashx",
data: encodeBase64(docxData),
contentType: "application/json; charset=utf-8",
}).done(function (data) {
document.getElementById("documentXmlContent").textContent = data;
}).fail(function (jqXHR, textStatus) {
});
}
You may find more information from here:
https://github.com/pkkj/AppForOfficeSample/tree/master/GetFileAsync
Hope this could help.
Additional to Keyjing Peng's answer (which I found very helpful, thanks!) I thought I'd share a variation on the encodeBase64, which you don't want to do if you are uploading via REST to SharePoint. In that case you want to convert the byte array to a Uint8Array. Only then could I get it into a SharePoint library without file corruption.
var uArray = new Uint8Array(docdata);
Hope this helps someone, couldn't find this info anywhere else online...
See this link
http://msdn.microsoft.com/en-us/library/office/jj715284(v=office.1501401).aspx
it contains this example method:
var i = 0;
var slices = 0;
function getDocumentAsPDF() {
Office.context.document.getFileAsync("pdf",{sliceSize: 2097152}, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then
// result.value will return a valid File Object.
myFile = result.value;
slices = myFile.sliceCount;
document.getElementById("result").innerText = " File size:" + myFile.size + " #Slices: " + slices;
// Iterate over the file slices.
for ( i = 0; i < slices; i++) {
var slice = myFile.getSliceAsync(i, function (result) {
if (result.status == "succeeded") {
doSomethingWithChunk(result.value.data);
if (slices == i) // Means it's done traversing...
{
SendFileComplete();
}
}
else
document.getElementById("result").innerText = result.error.message;
});
}
myFile.closeAsync();
}
else
document.getElementById("result2").innerText = result.error.message;
});
}
change "pdf" to "compressed" and the method call doSomethingWithChunk() needs to be created and should probably do something like this:
function base64Encode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
I use this technique to successfully save to Azure blob storage.
Obviously you should rename the method as well.

Programs with Javascript json parsing

I am trying to parse a json object and try to do an alert in js if a particular word is detected in the json string,
CloudPush.addEventListener('callback', function (evt) {
//alert(evt);
alert(evt.payload);
var jsonNotification = JSON.parse(evt.payload);
for (var i = 0; i < jsonNotification.length; i++) {
var text = new String(jsonNotification[i]);
if (text == 'Hello') {
alert('Hello');
}else{
alert('Error');
}
}
I am however getting some errors that the alert 'Hello' does not display. Not really sure if I am doing it correctly. Hopefully someone can shed some light.
CloudPush.addEventListener('callback',
function (evt) {
// parse the desired data
var data= JSON.parse(evt.payload),
key;
// loop over all the keys of the JSON object
for (key in data) {
if(data.hasOwnProperty(key)){
alert( data[key] === 'Hello' ? 'Hello' : 'Error' );
}
}
);

Categories