Error in generating multidimensional array from JSON array - javascript

I use JavaScript to obtain data from server through PHP.
PHP obtains data from MySQL, encodes it to JSON data and sends it via HTTP protocol to the client - in my case, that is browser.
JavaScript i.e. as shown below picks those values up and renders the chart. Only for testing I'm printing out conversion of the JSONArray to a StringArray which is the output of the PHP.
Any suggestions as to why when my JS code gets to the point below
myLogger("myLogger - newObject.dummmysetsJSONArr.entryID" + newObject.dummmysetsJSONArr.entryID);
it throws the following error as seen in the console:
uncaught typeerror cannot read property 'entryID' of undefined
Here's an example of the DB data converted into JSON:
{"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}
And here's my JS:
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var req = false;
var jsonarry;
try {
// most browsers
req = new XMLHttpRequest();
myLogger("myLogger - XMLHttpRequest() created");
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
myLogger("myLogger - req = new ActiveXObject(Msxml2.XMLHTTP);");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
myLogger("myLogger - req = new ActiveXObject(Microsoft.XMLHTTP);");
} catch (e){
}
}
}
if (!req) {
myLogger("req === false");
} else {
myLogger("req === true");
}
// Use onreadystatechange property
req.onreadystatechange = function() {
//myLogger("myLogger - req.onreadystatechange = function(){");
if(req.readyState == 4) {
myLogger("myLogger - req.readyState == 4");
if(req.status === 200) {
myLogger("myLogger - req.status === 200");
jsonarry = req.responseText;
myLogger("myLogger - JSON ARRAY - " + jsonarry);
myLogger(" ------------- ");
var identedText = JSON.stringify(jsonarry, null, 4);
var jsonString = JSON.stringify(jsonarry);
myLogger("myLogger - Unindented jsonString - " + jsonString);
var newObject = JSON.parse(jsonString);
myLogger("myLogger - newObject " + newObject);
myLogger("myLogger - newObject.dummmysetsJSONArr.entryID" + newObject.dummmysetsJSONArr.entryID);
}
function myLogger(content) {
if (window.console && window.console.log) {
console.log("myLogger - " + content);
}
}
Edit: I've reduced my OP code to the by removing the irrelevant bits.
Any ideas are appreciated

the error is on this line
myLogger("myLogger - newObject.dummmysetsJSONArr.entryID" + newObject.dummmysetsJSONArr.entryID);
when you try to log newObject.dummmysetsJSONArr.entryID.
Indeed, newObject.dummmysetsJSONArr.entryID is undefined since newObject.dummmysetsJSONArr is an array.
For example, newObject.dummmysetsJSONArr[0].entryID would be valid.

Related

XMLHttpRequest does not execute in a Safari

BackGround
Currently working on a webpage which must work for both Mac OS and Windows. Currently. I have tested this code on IE and it works great, however when it comes to Mac OS it seems to now execute correctly as how it does with Windows.
Problem
I isolated the issue which is causing the problem in Mac OS. This call out to a Sharepoint Doc lib, which in turn returns a byte array that I later create a Base64 string is causing the issue. I have read the doc on the compatibility of XMLHttpRequest with Safari in the below and shows that it is compatible. Not sure why it work so well in IE but does not work in Safari.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Code
function GetImgB64(relativeUrl) {
var defferedVarVlalue = jQuery.Deferred();
var b64Img;
$.when(TokenForSharePoint()).then(function (sharepointToken) {
var url = "https://<tenant>.com/sites/<site>/_api/web/GetFileByServerRelativeUrl('" + relativeUrl + "')/$value";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, false);
xmlhttp.setRequestHeader("Authorization", "Bearer " + sharepointToken);
xmlhttp.responseType = 'arraybuffer';
xmlhttp.onloadend = function (e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arr = new Uint8Array(this.response);
var raw = '';
var i, j, subArray, chunk = 5000;
for (i = 0, j = arr.length; i < j; i += chunk) {
subArray = arr.subarray(i, i + chunk);
raw += String.fromCharCode.apply(null, subArray);
}
b64Img = btoa(raw);
}
else {
errorResults.Location = url;
errorResults.ErrorCode = xmlhttp.status;
errorResults.ErrorResponseText = xmlhttp.statusText;
errorResults.ErrorMessage = "Unable to Load Image",
ErrorHandler(errorResults);
}
};
xmlhttp.onerror = function (error) {
MessageWindow();
};
xmlhttp.send();
return defferedVarVlalue.resolve(b64Img);
});
return defferedVarVlalue.promise();
};
also my script doesn't work with safari

TypeError: Cannot read property 'open' of undefined (Phonegap and Ionic)

I'm building a mobile app using Phonegap Build and Ionic. I am trying to make an XMLHttpRequest to a web service to get some XML data. The web service requires 3 parameters. I keep getting the following error:
ionic.bundle.js:26794 TypeError: Cannot read property 'open' of
undefined.
Any ideas as to what I might be doing wrong?
I have attached the entire method below.
$scope.result = function callService(requestAction, requestXML){
var httpObj = undefined;
if(window.XMLHttpRequest){
httpObj = new XMLHttpRequest();
}
else if (window.ActiveXObject){
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
if(httpObj = undefined){
alert("Failed creating Http Object");
return "";
}
if(requestAction == undefined || requestAction == null){
requestAction = "";
}
var async = false;
var url = "theurl";
var systemID = "thesystemid";
var requestAction = "GetEnquiry";
var requestXML = "therequestxml";
var params = "SystemID=" + systemID + "&RequestAction=" + requestAction + "&RequestXML=" + requestXML + "&OutputFormat=JSON";
var headers = "Content-type , application/x-www-form-urlencoded; charset=UTF-8";
httpObj.open("POST", url, async);
httpObj.send(params);
if(httpObj.readyState == 4 && httpObj.status == 200){
var result = httpObj.responseText;
console.log("This is the result: " + result);
return result;
}
else {
var result = httpObj.responseText;
return result;
}
};
})
The problem is the httpObj object which is undefined and you try to access a method on undefined. The reason why you don't show the error message (when httpObj is undefined) you have defined in the alert is that you condition is not correct. This
if(httpObj = undefined){
should had been like below:
if(httpObj === undefined){
or equivalently like:
if(httObj){

upload zip file to Node.js via Ajax

How to load zip files to the server node js without forms, just using ajax, and unpack this.
I'm trying to do it like:
function sendAjax(request) {
xhr = new XMLHttpRequest();
xhr.open(request.method, request.url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200){
if (request.callback) {
request.callback(JSON.parse(xhr.response));
}
}
};
var data = null;
if (request.multipleData !== true) {
data = JSON.stringify(request.data);
} else {
var fd = new FormData();
fd.append('file.zip', request.data);
data = fd;
}
xhr.send(data);
}
on the server side I'm doing next:
var body = '';
request.on('data', function (data) {console.log(1111 + data);
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e8) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
request.connection.destroy();
}
});
request.on('end', function () {console.log(222 + body);
router.route(url.parse(request.url, true), response, body);
});
and
var buf = new Buffer(file.length);
buf.write(file);
var zip = new AdmZip(buf);
var zipEntries = zip.getEntries(); // an array of ZipEntry records
for (var i = 0; i < zipEntries.length; i++) {
console.log(zip.file("content.txt").asText());
But I'm getting error,
...server\node_modules\adm-zip\zipFile.js:66
throw Utils.Errors.INVALID_FORMAT;
^
Invalid or unsupported zip format. No END header found
What the problem?

Unexpected end of input error with chrome.tabs.query

I've been struggling with this and have had no luck. I've included the error and most of the context around the block in question.
var successURL = 'https://www.facebook.com/connect/login_success.html';
var userFirstName = ''
var userEmail = ''
function onFacebookLogin(){
if (localStorage.getItem('accessToken')) {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.indexOf(successURL) !== -1) {
var params = tabs[i].url.split('#')[1];
var accessToken = params.split('&')[0];
accessToken = accessToken.split('=')[1];
localStorage.setItem('accessToken', accessToken);
chrome.tabs.remove(tabs[i].id);
console.log(accessToken);
pullSecurityToken();
findFacebookName();
}
}
});
}
}
chrome.tabs.onUpdated.addListener(onFacebookLogin);
function pullSecurityToken(){
var pointUrl = "localhost:3000/api/v1/retrieve_token_for/" + localStorage.accessToken + "/" + localStorage.securityToken;
var xhr = new XMLHttpRequest();
xhr.open("GET", pointUrl, true);
alert(JSON.parse(xhr.responseText));
}
var response = ''
function findFacebookName(){
if (localStorage.accessToken) {
var graphUrl = "https://graph.facebook.com/me?access_token=" + localStorage.accessToken;
console.log(graphUrl);
var xhr = new XMLHttpRequest();
xhr.open("GET", graphUrl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == '401'){
alert("Security Token Invalid, please check and try again.");
}
response = JSON.parse(xhr.responseText);
userFirstName = response.first_name
userEmail = response.email
console.log(response);
}
}
}
xhr.send();
}
Here's the error:
Error in response to tabs.query: SyntaxError: Unexpected end of input
at onFacebookLogin (chrome-extension://dapeikoncjikfbmjnpfhemaifpmmgibg/background.js:7:17)
Even if you use a synchronous request, you still need to send it. So add an xhr.send(); after the xhr.open inside pullSecurityToken.
As Felix Kling points out in the comments, the lack of send will directly cause your error, because the responseText property is still an empty string and such a string is not valid JSON whereas "" would be valid JSON.

Returning an array and storing into another array, creating a multidimensional array

EDIT: I've tried to implemented the solution, but it still doesn't work. Sorry i'm a programming idiot. Thanks for the link to the page.
In my first function databaseBOscreens i am attempting to obtain symbols of stocks according to the filter selected for a broker and/or an asset class. The function sends a request to another file which performs SELECT statement to lookup for the relevant symbols using mysqli. The result would be an array of symbols, which i then encode and subsequently parsed in this js function.
Each symbol will then go through a second process, which is my second function generatePrice() to obtain the historical prices for that particular symbol. What i'm trying to do is to loop through all symbols to generate and store the priceArr as an array in the resultArr. Sorry for being unclear.
function databaseBOscreens(broker,assetClass) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "broker=" + broker + "&category=" + assetClass;
xhr.open("POST", "generateSymbol.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = receive_data;
function receive_data() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var resultArr = JSON.parse(xhr.responseText);
var priceArr = new Array();
for(var ctr=0;ctr<resultArr.length;ctr++)
{
generatePrice(function(result,resultArr[ctr].symbol)){
priceArr[ctr] = result;
}
}
}
}
}
function generatePrice(callback,symbol) {
var xhr2;
if (window.XMLHttpRequest) {
xhr2 = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
}
var data2 = "symbol=" + symbol;
xhr2.open("POST", "generatePrice.php", true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send(data2);
xhr2.onreadystatechange = receive_data2;
function receive_data2() {
if (xhr2.readyState === 4)
{
if (xhr2.status === 200)
{
var priceArr = JSON.parse(xhr2.responseText);
callback(priceArr);
}
}
}
}
function receive_data() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var resultArr = JSON.parse(xhr.responseText);
var priceArray = new Array();
for(var ctr=0;ctr<resultArr.length;ctr++)
{
priceArray = generatePrice(resultArr[ctr].symbol);
}
alert(priceArray.length);
}
}
My function generatePrice() returns an array, but i can't seem to store it in another array to create a multidimensional array. I've search everywhere i can't seem to get it work. Thanks in advance for any help rendered
generatePrice function:
function generatePrice(symbol) {
var xhr2;
if (window.XMLHttpRequest) {
xhr2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
}
var data2 = "symbol=" + symbol;
xhr2.open("POST", "generatePrice.php", true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send(data2);
xhr2.onreadystatechange = receive_data2;
function receive_data2() {
if (xhr2.readyState == 4 && xhr2.status == 200)
{
var priceArr = JSON.parse(xhr2.responseText);
return priceArr;
}
}
}
My function generatePrice() returns an array,
No it doesn't, it returns undefined. XHR is asynchronous, see How do I return the response from an asynchronous call?.
priceArray = generatePrice(resultArr[ctr].symbol);
I can't seem to store it in another array
You didn't attempt to do so, you just stored the result of every call in the priceArray variable - instead of in a property of the array. Use
priceArray[ctr] = generatePrice(resultArr[ctr].symbol);
// or
priceArray.push( generatePrice(resultArr[ctr].symbol) );

Categories

Resources