XMLHttpRequest is showing a msg error in the browser - javascript

I did a function to show a div when i open my html(its working fine, the div shows at open), but i get this error:
var getJSON = function (url, callback) {
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'json';
ajax.onreadystatechange = function () {
var status = ajax.status;
if (status === 200) {
callback(status, ajax.response);
} else {
callback(null, ajax.response);
}
};
ajax.send();
};
getJSON('games.json', function (err, data) {
if (err === null) {
console.log('Error' + err);
} else {
var bets = document.getElementById('bets-container-lotos');
bets.innerHTML = '';
bets.innerHTML +=
'<button id="bets-lotofacil-color" class="bets-lotofacil" onclick=lotofacil()>' +
data.types[0].type +
'</button>';
}
});

Related

Loading data using Ajax for mentions using Tribute.js

Hello I am trying to use tribute.js to load data. However, I face an error, Unable to append to values, as it is a function. Currently my configuration is:
$(document).ready(function () {
var tribute = new Tribute({
values: function (search, cb) {
getUsernames(search, users => cb(users))
},
menuItemTemplate: function (item) {
return '<img src="'+item.original.img.url + '">' + item.original.name + " " + item.original.last;
},
selectTemplate: function (item) {
return '#' + item.original.username;
},
});
tribute.attach(document.getElementById("id_content"));
function getUsernames(search, cb){
var xhr = new XMLHttpRequest();
xhr.open('GET', '/get/user/mentions?q='+search, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
cb(data);
if (xhr.readyState == 4 && xhr.status == "200") {
$.each(data, function(i, item) {
tribute.append(0,[
{
name: item.first_name,
last: item.last_name,
username:item.username,
img: item.image
},
]);
});
} else if (xhr.status === 403) {
cb([]);
}
}
xhr.send(null);
}
})
Which the each loop is causing the issue, I was wondering how I can load the data from Ajax correctly?

How can i display as ajax-response in a reloaded page

I have the following situation in an AJAX-Request:
function getFileContens(OBJ) {
var file = OBJ.id;
PARAMS = "Action=getFileContens";
PARAMS = PARAMS + "&File=" + OBJ.id;
var probenZahl = file.split("__")[4];
document.getElementById("inpProbenAnzahl").value = probenZahl;
//setSessionValue(document.getElementById("inpProbenAnzahl"));
try {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Ihr Webbrowser unterstuetzt leider kein Ajax!");
}
//alert(PARAMS);
req.open("POST", "./php/ajax/Eingabe.php", true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = function() {
cbGetFileContens();
};
req.send(PARAMS);
} catch (e) {
alert("Fehler: " + e);
}
}
function cbGetFileContens() {
if (4 == req.readyState) {
if (200 != req.status) {
alert("Fehler " + req.status + ": " + req.statusText);
} else {
//alert(req.responseText);
var ar_resp = req.responseText.split(";;;");
for (let i = 0; i < ar_resp.length; i++) {
ar_inp = ar_resp[i].split("##");
if (ar_inp[0].trim().length > 2) {
if (document.getElementById(ar_inp[0].trim())) {
document.getElementById(ar_inp[0].trim()).value = ar_inp[1];
}
}
}
location.reload();
//console.log("Hallo");
console.log(req.responseText);
}
}
}
This code shoud display the splitted response-text in a textfield with certain IDs in a HTML-File...
I want to use the Ajax-response-text after reloading the page..
Everything works fine whe i do not reload the page..
Using reloading the text is not displayed..
You can store the response into a session storage.
sessionStorage.setItem('ajax_response', req.responseText)
location.reload();
After, when the page is loaded, you can put the item into your element.
var el = document.getElementById('elemId')
el.innerText = sessionStorage.getItem('ajax_response')

Dynamics JavaScript Web Resource rendered as HTML

When running my JavaScript, fires on button click on the form pictured left, I get several logs at points in my code. The JavaScript fires off an XHR request to an external API.
When I click into any of the links to my file from the console output I'm brought there. Before I would navigate to my JavaScript file, but can not seem to anymore.
JavaScript source code
function HandleSyncTask(commandProperties, primaryControl) {
console.log("HandleSyncTask running...");
openSyncTaskConfirmDialog(commandProperties, primaryControl);
}
function openSyncTaskConfirmDialog(commandProperties, primaryControl) {
console.log("Opening confirm dialog...");
var confirmStrings = {
cancelButtonLabel: "No",
confirmButtonLabel: "Yes",
title: "Preparing Tasks Sync",
subtitle: "Are you sure you want to Sync Tasks?"
};
var confirmOptions = { height: 200, width: 450 };
Xrm.Navigation.openConfirmDialog(confirmStrings, confirmOptions).then(
success => {
if (success.confirmed) {
console.log("openSyncTaskConfirmDialog confirmed.");
getOrgTasks(commandProperties, primaryControl);
}
else {
console.log("openSyncTaskConfirmDialog closed.");
}
},
error => {
console.log(error.message);
});
}
function openSyncTaskCompleteDialog() {
var alertStrings = { confirmButtonLabel: "Okay", text: "Sync task complete" };
var alertOptions = { height: 120, width: 260 };
Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(
function success(result) {
console.log("openSyncTaskCompleteDialog dialog closed");
},
function (error) { concole.log(error.message); }
);
}
function getOrgTasks(commandProperties, primaryControl) {
console.log("In getOrgTasks");
var stsToken = "";
var tokenReq = new XMLHttpRequest();
var tokenReqParams = "grant_type=password&scope=OrgApi&username={REMOVED FOR STACKOVERFLOW}&password={REMOVED FOR STACKOVERFLOW}";
tokenReq.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
if (this.status == 200) {
console.log("SUCCESS sts/connect/token");
var tokenObject = JSON.parse(this.responseText);
stsToken = tokenObject.access_token.toString();
}
}
});
tokenReq.open("POST", "https://orgdev.azurewebsites.net/sts/connect/token", true);
taskReq.setRequestHeader("Accept", "application/json");
tokenReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
tokenReq.setRequestHeader("Authorization", "Basic {REMOVED FOR STACKOVERFLOW}");
tokenReq.setRequestHeader("Cache-Control", "no-cache");
console.log("About to SEND sts/connect/token");
tokenReq.send(tokenReqParams);
var challengeTasks = [];
var orgConfigurationEntityReference = primaryControl.getGrid().getRows().get(0).data.entity.getEntityReference();
var orgConfigurationEntityType = orgConfigurationEntityReference["entityType"].toString();
var orgConfigurationGuid = orgConfigurationEntityReference["id"].toString();
Xrm.WebApi.retrieveRecord(orgConfigurationEntityType, orgConfigurationGuid, "?$expand=org_org_orgconfiguration_org_orgchallenge_orgconfigurationid").then(
function success(result) {
console.log("SUCCESS retrieveRecord");
var taskReq = new XMLHttpRequest();
taskReq.withCredentials = true;
taskReq.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
if (this.status == 200) {
challengeTasks = JSON.parse(this.responseText);
}
}
});
taskReq.open("GET", `https://orgdev.azurewebsites.net/api/${result.org_org_orgconfiguration_org_orgchallenge_orgconfigurationid[0]["org_orgid"]}/tasks`, false);
taskReq.setRequestHeader("Accept", "application/json");
taskReq.setRequestHeader("Authorization", "Bearer " + stsToken);
taskReq.setRequestHeader("Content-Type", "application/json");
taskReq.setRequestHeader("Cache-Control", "no-cache");
taskReq.send();
var orgTrigger = { };
var orgEntityName = "";
Xrm.Utility.showProgressIndicator("Syncing Tasks...");
for (var i = 0; i < challengeTasks.length; i++) {
orgEntityName = challengeTasks[i].primaryobjecttypecode[0].toUpperCase() + challengeTasks[i].primaryobjecttypecode.slice(1);
orgTrigger =
{
"org_name": challengeTasks[i].name + " " + orgEntityName,
"org_entityname": orgEntityName,
"org_messagename": challengeTasks[i].name,
// org_org_orgtask_org_orgtrigger
// navigation property (1:N), DataModel/orgCrmSdkTypes, generated class using the CrmSvcUtil.exe
"org_org_orgtrigger_org_orgtask_orgtriggerid":
[
{
"org_name": challengeTasks[i].Title,
"org_orgtaskidreference": challengeTasks[i].TaskId,
"org_enabled": true,
"org_pointvalue": challengeTasks[i].EligiblePoints
}
]
};
Xrm.WebApi.createRecord("org_orgtrigger", orgTrigger).then(
function success(result) {
console.log("Created task and attached trigger to it, trigger is " + orgTrigger);
},
function (error) {
console.log("ERROR: Xrm.WebApi.createRecord " + error.message.toString());
}
);
}
setTimeout(function() {
console.log("Creating an illusion of loading something");
Xrm.Utility.closeProgressIndicator();
openSyncTaskCompleteDialog();
}, 5000);
},
function (error) { console.log(error.message); }
);
}
Removing all setRequestHeader that accept json fixed my issue. Also implemented Promises and chain calls in the new implementation to enforce the order I want to data to arrive in my solution.
So remove each line that has.
{request var name goes here}.setRequestHeader("Accept", "application/json");

Direct upload string to s3 from bootstrap modal not working

I observed a very strange behavior. If I set a button from web to upload string to S3, it works fine. But if I set a button from web to bring up a bootstrap modal, then from this modal I set a button to upload the string, it doesn't work.
Frontend is like below in both cases. The difference is whether clicking to run function 'saveToAWS' from web or from modal as 2-step-process, the latter returns xhr.status as 0.
function saveToAWS() {
var file = new File([jsonStr], "file.json", { type: "application/json" });
var xhr = new XMLHttpRequest();
var fn=file.name;
var ft = file.type;
xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log('signiture returned')
save_file(file, response.signed_request, response.url);
}
else {
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
function save_file(file, signed_request, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', signed_request);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('200');
}
else {
alert('cannot upload file');
}
}
};
xhr.send(file);
}
Backend as Node.js, in order to get a signed URL:
app.get('/sign_s3_save', isLoggedIn, function (req, res) {
var fileName = req.query['file-name'];
var fileType = req.query['file-type'];
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var ac = req.user._id;
var timenow = Date.now().toString();
var fileRename = ac + '/json/' + timenow + '.json';
var s3_params = {
Bucket: S3_BUCKET,
Key: fileRename,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, data) {
if (err) {
console.log(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
Any suggestion, please?

consuming API JSon calls through TVJS-tvOS

I am trying to play with tvOS, and I have small question regarding handling json call. I have to get some data through an API, let's say for sake of test that I am calling this link
http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json
I tried to use this function with some modification
function getDocument(url) {
var templateXHR = new XMLHttpRequest();
templateXHR.responseType = "json";
templateXHR.open("GET", url, true);
templateXHR.send();
return templateXHR;
}
but didn't work out. Any hints or help ?
If I need to use NodeJS, how can I do that ?
This is one that I got working. It's not ideal in many respects, but shows you something to get started with.
function jsonRequest(options) {
var url = options.url;
var method = options.method || 'GET';
var headers = options.headers || {} ;
var body = options.body || '';
var callback = options.callback || function(err, data) {
console.error("options.callback was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
} else {
callback(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
callback(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(method, url, true);
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
xhr.send();
return xhr;
}
And you can call it with the following example:
jsonRequest({
url: 'https://api.github.com/users/staxmanade/repos',
callback: function(err, data) {
console.log(JSON.stringify(data[0], null, ' '));
}
});
Hope this helps.
I tested this one out on the tvOS - works like a charm with jQuery's syntax (basic tests pass):
var $ = {};
$.ajax = function(options) {
var url = options.url;
var type = options.type || 'GET';
var headers = options.headers || {} ;
var body = options.data || null;
var timeout = options.timeout || null;
var success = options.success || function(err, data) {
console.log("options.success was missing for this request");
};
var contentType = options.contentType || 'application/json';
var error = options.error || function(err, data) {
console.log("options.error was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (xhr.responseType === 'json') {
success(null, xhr.response);
} else {
success(null, JSON.parse(xhr.responseText));
}
} else {
success(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
error(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", contentType);
xhr.setRequestHeader("Accept", 'application/json, text/javascript, */*');
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
if(!body) {
xhr.send();
} else {
xhr.send(body);
}
return xhr;
}
Example queries working on Apple TV:
var testPut = function(){
$.ajax({
type: 'PUT',
url: url,
success: successFunc,
error: errFunc,
dataType: 'json',
contentType: 'application/json',
data: data2
});
}
var testGet = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
var getLarge = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
Did you call your function in the 'App.onLaunch'
App.onLaunch = function(options) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json';
var doc = getDocument(url);
console.log(doc);
}
Might be worth looking at https://mathiasbynens.be/notes/xhr-responsetype-json
I came across this question looking to accomplish the same thing, and was inspired by #JasonJerrett's answer, but found it a bit lacking because in my instance I am using an XML template built in Javascript like this:
// Index.xml.js
var Template = function() {
return `very long xml string`;
};
The issue is that you can't perform the XHR request inside the template itself, because the template string will be returned back before the XHR request actually completes (there's no way to return data from inside an asynchronous callback). My solution was to modify the resource loader and perform the XHR request there, prior to calling the template and passing the data into the template function:
ResourceLoader.prototype.loadResource = function(resource, dataEndpoint, callback) {
var self = this;
evaluateScripts([resource], function(success) {
if (success) {
// Here's the magic. Perform the API call and once it's complete,
// call template constructor and pass in API data
self.getJSON(dataEndpoint, function(data) {
var resource = Template.call(self, data);
callback.call(self, resource);
});
} else {
var title = "Failed to load resources",
description = `There was an error attempting to load the resource. \n\n Please try again later.`,
alert = createAlert(title, description);
Presenter.removeLoadingIndicator();
navigationDocument.presentModal(alert);
}
});
}
// From: https://mathiasbynens.be/notes/xhr-responsetype-json
ResourceLoader.prototype.getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
Then the template function needs to be modified to accept the incoming API data as a parameter:
// Index.xml.js
var Template = function(data) {
return 'really long xml string with injected ${data}';
};
You need to implement the onreadystatechange event on the XHR object to handle the response:
templateXHR.onreadystatechange = function() {
var status;
var data;
if (templateXHR.readyState == 4) { //request finished and response is ready
status = templateXHR.status;
if (status == 200) {
data = JSON.parse(templateXHR.responseText);
// pass the data to a handler
} else {
// handle the error
}
}
};
If you want to call the request on app launch, just add in application.js:
App.onLaunch = function(options) {
var javascriptFiles = [
`${options.BASEURL}js/resourceLoader.js`,
`${options.BASEURL}js/presenter.js`
];
evaluateScripts(javascriptFiles, function(success) {
if(success) {
resourceLoader = new ResourceLoader(options.BASEURL);
var index = resourceLoader.loadResource(`${options.BASEURL}templates/weatherTemplate.xml.js`, function(resource) {
var doc = Presenter.makeDocument(resource);
doc.addEventListener("select", Presenter.load.bind(Presenter));
doc.addEventListener('load', Presenter.request);
navigationDocument.pushDocument(doc);
});
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
});
}
In presenter.js add a method:
request: function() {
var xmlhttp = new XMLHttpRequest() , method = 'GET' , url = 'your Api url';
xmlhttp.open( method , url , true );
xmlhttp.onreadystatechange = function () {
var status;
var data;
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
if (status == 200) {
data = JSON.parse(xmlhttp.responseText);
console.log(data);
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
}
};
xmlhttp.send();
},

Categories

Resources