XMLHttpRequest does not execute in a Safari - javascript

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

Related

data uploading by ajax in iOS webview

In iOS webview I have implemented file uploading:
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { ... };
xhr.send(blobOrFile);
}
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
var blob = this.files[0];
const BYTES_PER_CHUNK = 1024 * 1024; // 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while(start < SIZE) {
upload(blob.slice(start, end));
start = end;
end = start + BYTES_PER_CHUNK;
}
}, false);
})();
This JavaScript work well in all browser, but in iOS webview it send empty POST ?
Before send I tried to alert() blob length was correct, but in server side I get 0 content length. What can cause this problem and is possible to fix this from JS side ?

Parsing a web page using Javascript (ajax and jquery involved)

Trying to parse an ajax requested page for the word "function" and store the last matched character in an array. The only errors JSLint is returning are
unexpected ('space')
and
Combine this statement with the previous 'var' statement,
neither of which I believe should effect whether or not the code is executed. Any help is appreciated.
/*jslint browser: true*/
/*global $, jQuery, alert*/
$(document).ready(function () {
"use strict";
//retrieve page
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://abs.twimg.com/c/swift/en/init.27d18bf5a2b7d3e5fbcdbb86f85e7a534b11f06b.js", true);
xhr.responseType = "text";
xhr.send();
xhr.onload = function () {
//set variables to be compared
var page = xhr.responseText;
var word = "function";
//page and word locations
var i = 0;
var n = 0;
var page_loc = page[i];
var word_loc = word[n];
//matched result storage
var chain = [""];
// compare
while (n < word.length - 1) {
if (page_loc === word_loc) {
n = n + 1;
i = i + 1;
console.log(i);
} else {
i = i + 1;
}
}
//place matched result
chain.push(page_loc);
console.log(chain);
};
});
So regarding your comment and question.
You don't need to iterate over that string, if you only want to check whether a given string is present in a response, you can use a built-in function indexOf() or in newer browsers includes().
So the code would look as follow:
$(document).ready(function () {
"use strict";
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://abs.twimg.com/c/swift/en/init.27d18bf5a2b7d3e5fbcdbb86f85e7a534b11f06b.js", true);
xhr.responseType = "text";
xhr.onload = function () {
var page = xhr.responseText;
var word = "function";
if (page.indexOf(word) !== -1)
console.log([word[word.length-1]]);
};
xhr.send();
});

js-xlsx Uncaught TypeError: console.log is not a function

I am using xlsx for reading Excel file. It kinda works... At least first row. I don't know what's the problem so here I am.
this is my code:
/* set up XMLHttpRequest */
var url = "http://localhost/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {type:"binary"});
/* DO SOMETHING WITH workbook HERE */
var alphabet = "ABC".split("");
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var address_of_cell, desired_cell, desired_value;
var descript;
for (i=1;i<30;i++) {
for (j=0;j<alphabet.length;j++) {
if (alphabet[j] == "A") {
console.log("This will be title: "+getValue(alphabet[j], i));
} else if (alphabet[j] == "B") {
descript = getValue(alphabet[j], i);
console.log(""+descript);
} else if (alphabet[j] == "C") {
console.log="This will be description: " + descript+" - "+getValue(alphabet[j], i);
}
}
}
function getValue (column, row) {
address_of_cell = column+''+row;
console.log(address_of_cell);
/* Find desired cell */
desired_cell = worksheet[address_of_cell];
/* Get the value */
desired_value = desired_cell.v;
return(desired_value);
}
};
oReq.send();
Now the result I get in console is:
A1
This will be title: VI/46/1998
B1
30-12-1998
C1
Uncaught TypeError: console.log is not a function Bookmarklet.js:43
As You can see in C1 I get that console.log is not a fucntion, but why? Where's my mistake? What am I doing wrong?
Sincerely,
Thomas
console.log is provided by the environment in which your code runs. Or not. It depends on the environment. Modern browsers provide it (at least if you have devtools open; some versions of IE don't provide it if you don't). NodeJS provides it.
Two possibilities:
Your environment doesn't provide it.
It does, but then you run this line of code:
console.log="This will be description: " + descript+" - "+getValue(alphabet[j], i);
which overwrites it with a string. Strings aren't functions, so the attempt to call it on any of your lines that use it correctly (like console.log(address_of_cell);) will now start failing.
That line should be like the others, a function call:
console.log("This will be description: " + descript+" - "+getValue(alphabet[j], i));

Error in generating multidimensional array from JSON array

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.

JavaScript extracting data from XML (if else statement not working)

So my problem in the code below is in the following if else if statement at the bottom:
1. the code in both of the if statements work perfect.
2. the issue is that when i run the code on one can be use.
if i do 2 separate if statements only the second one works.
if i do 1 if and one else if only the if statement works and the else if does nothing.
a little more info: what I'm trying to do is every time the function times out and loops through again it will check the if statements and if something changed to run the appropriate if clause.
PLEASE LET ME KNOW IF MORE INFO IS NEEDED.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create object");
else
return xmlHttp;
}
function process_search()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
search_parameter = encodeURIComponent(document.getElementById("userInput").value);
search_type = encodeURIComponent(document.getElementById("userOptions").value);
xmlHttp.open("GET", "../pages/search_xml.php?search_parameter=" + search_parameter + "&search_type=" + search_type, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process_search()',5000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
if(document.getElementsByTagName('find_users')) // FIND USERS
{
first_name = root.getElementsByTagName('first');
last_name = root.getElementsByTagName('last');
users = document.createElement('ul');
users.setAttribute("id", "usersFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< first_name.length; i++)
{
usersList = document.createElement('li');
t = document.createTextNode(first_name.item(i).firstChild.data + " - " + last_name.item(i).firstChild.data + "<br/>");
usersList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(usersList);
}
}else if(document.getElementsByTagName('find_config_item')) //FIND CONFIG ITEMS
{
item = root.getElementsByTagName('item');
desc = root.getElementsByTagName('description');
itemsList = document.createElement('ul');
itemsList.setAttribute("id", "itemsFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< item.length; i++)
{
itemList = document.createElement('li'); // CREATE LIST ITEM ELEMENT
t = document.createTextNode(item.item(i).firstChild.data + " - " + desc.item(i).firstChild.data + "<br/>");
itemList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(itemList);
}
}
setTimeout('process_search()', 5000);
}
else
{
alert("something is wrong");
}
}
}
You shouldn't really rely on try/catch for this use case. You can be fairly certain the XMLHttpRequest or a Mircrosoft.XMLHTTP object will exist so you could simplify your code to the following:
function createXmlHttpRequestObject () {
return window.XMLHttpRequest ? new XMLHttpRequest() : new XDomainRequest();
}
var xmlHttp = createXmlHttpRequestObject();
Let me know if you would like to see a non ternary version

Categories

Resources