Get JSON data from URL & display it using innerHTML - how? - javascript
I have the following code that grabs all the data from an array and then displays it in a certain div within an HTML document. Right now the data is embedded into the code, yet I need to grab this same data from a URL. As you can see I already started the XHR request & tested it's retrieval successfully. I'm just not sure once the data is grabbed from the URL how to display it within the HTML similarly as it works now?
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
// LOAD AND DISPLAY LOCATION DATA
window.onload=function(){
var data = [
{"id":1271832,"segment_id":3345,"latitude":37.7029,"longitude":-121.9335,"name":"Verve","address_1":"7886 Dublin Blvd","phone_number":"555-324-5678","postal_code":"94568","postal_code_id":"7168","metro":"San Francisco-Oakland-San Jose CA","city":"Dublin","region":"CA","country":"US","m":4934,"km":4.9,"miles":3.07},
{"id":1271836,"segment_id":3345,"latitude":37.6958,"longitude":-121.9255,"name":"Verve","address_1":"1 Stoneridge Mall Space","phone_number":"555-324-5678","postal_code":"94588","postal_code_id":"7169","metro":"San Francisco-Oakland-San Jose CA","city":"Pleasanton","region":"CA","country":"US","m":5045,"km":5,"miles":3.14},
{"id":1271831,"segment_id":3345,"latitude":37.6931,"longitude":-121.9262,"name":"Verve","address_1":"1120 Stoneridge Mall Drive","phone_number":"555-324-5678","postal_code":"94566","postal_code_id":"7167","metro":"San Francisco-Oakland-San Jose CA","city":"Pleasanton","region":"CA","country":"US","m":5325,"km":5.3,"miles":3.31},
{"id":1271827,"segment_id":3345,"latitude":37.6999,"longitude":-121.7452,"name":"Verve","address_1":"4408 Las Positas Rd","phone_number":"555-324-5678","postal_code":"94551","postal_code_id":"7138","metro":"San Francisco-Oakland-San Jose CA","city":"Livermore","region":"CA","country":"US","m":13375,"km":13.4,"miles":8.31},
{"id":1271826,"segment_id":3345,"latitude":37.6966,"longitude":-122.0771,"name":"Verve","address_1":"3450 Village Dr","phone_number":"555-324-5678","postal_code":"94546","postal_code_id":"7133","metro":"San Francisco-Oakland-San Jose CA","city":"Castro Valley","region":"CA","country":"US","m":16796,"km":16.8,"miles":10.44},
{"id":1271838,"segment_id":3345,"latitude":37.8948,"longitude":-122.0591,"name":"Verve","address_1":"1295 S Main St","phone_number":"555-324-5678","postal_code":"94596","postal_code_id":"7292","metro":"San Francisco-Oakland-San Jose CA","city":"Walnut Creek","region":"CA","country":"US","m":23294,"km":23.3,"miles":14.48},
{"id":1271833,"segment_id":3345,"latitude":37.7114,"longitude":-122.1638,"name":"Verve","address_1":"1285 Marina Boulevard","phone_number":"555-324-5678","postal_code":"94577","postal_code_id":"7170","metro":"San Francisco-Oakland-San Jose CA","city":"San Leandro","region":"CA","country":"US","m":24055,"km":24.1,"miles":14.95},
{"id":1271819,"segment_id":3345,"latitude":37.9499,"longitude":-121.9603,"name":"Verve","address_1":"5412 Ygnacio Valley Rd","phone_number":"555-324-5678","postal_code":"94521","postal_code_id":"7254","metro":"San Francisco-Oakland-San Jose CA","city":"Concord","region":"CA","country":"US","m":24926,"km":24.9,"miles":15.49},
{"id":1271817,"segment_id":3345,"latitude":37.9435,"longitude":-121.7376,"name":"Verve","address_1":"2520 Sand Creek Rd","phone_number":"555-324-5678","postal_code":"94513","postal_code_id":"7248","metro":"San Francisco-Oakland-San Jose CA","city":"Brentwood","region":"CA","country":"US","m":27090,"km":27.1,"miles":16.84},
{"id":1271820,"segment_id":3345,"latitude":37.9452,"longitude":-122.0627,"name":"Verve","address_1":"157 Crescent Plaza","phone_number":"555-324-5678","postal_code":"94523","postal_code_id":"7256","metro":"San Francisco-Oakland-San Jose CA","city":"Pleasant Hill","region":"CA","country":"US","m":28030,"km":28,"miles":17.42}
];
data.forEach(function (item) {
pios(item)
})
function pios(item) {
var p = document.createElement('p');
p.id = item.id;
p.innerHTML = item.address_1 + '<br>' + item.city + item.region + item.postal_code;
document.getElementById('locations').appendChild(p)
}
}
<div id="locations"></div>
You need to add the onreadystatechange to your xhr:
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
data.forEach(function (item) {
pios(item);
});
}
}
xhr.open("GET", url, true);
xhr.send();
This includes the full methods you provided and linked it into the onload.
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
data.forEach(function (item) {
pios(item);
});
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send();
};
function pios(item) {
var p = document.createElement('p');
p.id = item.id;
p.innerHTML = item.address_1 + '<br>' + item.city + item.region + item.postal_code;
document.getElementById('locations').appendChild(p)
}
Figured this out and wanted to share. Thanks for the help!
***Don't forget to change http://example.com with the URL to your JSON data.
function getData(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send();
}
function renderData(data) {
console.log(data);
var html = data.pois.slice(0,3).reduce(function (frag, item) {
frag.appendChild(pios(item));
return frag;
}, document.createDocumentFragment());
document.getElementById('locations').appendChild(html);
}
function pios(item) {
var p = document.createElement('pre');
p.id = item.id;
p.textContent = item.address_1 + '\n' + item.city + ' ' + item.region + ' ' + item.postal_code;
return p;
}
getData(renderData);
<div id="locations"></div>
Related
Https reqest to get Gift card balance with JavaScript
I want to build a balance checker for Paysafecards for my own site. (JavaScript and HTML) https://www.paysafecard.com/en/balance-check/ has the function that i would need, but i want the function on my own site. I testet a little bit with Codex and the best was this: var paysafecard = document.createElement('div'); paysafecard.innerHTML = '<input type="text" id="paysafecard" placeholder="Enter your PaysafeCard PIN" />'; paysafecard.innerHTML += '<button id="checkBalance">Check Balance</button>'; paysafecard.innerHTML += '<div id="balance"></div>'; document.body.appendChild(paysafecard); document.getElementById('checkBalance').addEventListener('click', function() { var pin = document.getElementById('paysafecard').value; var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://www.paysafecard.com/en/balance-check/' + pin, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var balance = xhr.responseText.match(/<span class="amount">(.*?)<\/span>/); if (balance) { document.getElementById('balance').innerHTML = 'Balance: ' + balance[1]; } else { document.getElementById('balance').innerHTML = 'Invalid PIN'; } } }; xhr.send(); }); but it dosent really work.
Microsoft Dynamics 2016 - Javascript Banner
I would like to utilize Xrm.Page.ui.setFormNotification to display a banner at the top of a Shipment record. This banner would only appear for Shipments where the related entity Account is classified as "Service Watch". I'm pretty new to Javascript so I'm a bit lost how to pull values from related entities of a record to use. Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch", "WARNING") EDIT: Code working; function checkServiceWatch() { try{ var account = Xrm.Page.getAttribute("cmm_account").getValue(); var accountid = account[0].id; var formattedGuid = accountid.replace("}", ""); accountid = formattedGuid.replace("{", ""); "/api/data/v8.2/accounts(" + accountid + ")? $select=cmm_servicewatch"); var req = new XMLHttpRequest(); req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", true); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.onreadystatechange = function() { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 200) { var result = JSON.parse(this.response); var serviceWatch = result["cmm_servicewatch"]; // alert("serviceWatch: " + serviceWatch); if(serviceWatch) //set notification { Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1"); } // else // { // //Xrm.Page.ui.clearFormNotification("1"); // } } else { Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText); } } }; req.send(); } catch (err) { alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message); } }
You have to query the Account lookup record on form load to pull the extra attribute which says "Service watch" and show the notification banner if so. You can refer this community thread & use the sample code as is or Xrm.Webapi method to do it based on your CRM version. function checkAccount(){ var accountid = Xrm.Page.data.entity.attributes.get("new_parentaccount").getValue()[0].id; if (accountid.startsWith("{") && accountid.endsWith("}")) { accountid = accountid.slice(1, accountid.length - 1); } var req = new XMLHttpRequest(); req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=new_servicewatch", true); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.onreadystatechange = function() { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 200) { var result = JSON.parse(this.response); var serviceWatch = result["new_servicewatch"]; if(serviceWatch) //set notification { Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1"); } else { //Xrm.Page.ui.clearFormNotification("1"); } } else { Xrm.Utility.alertDialog(this.statusText); } } }; req.send(); }
How to add Node.js result in my HTML project?
this is my project: http://cryptotipsitalia.sytes.net/. I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price. How can I add it? That's my code: function getValueBTC() { <!-- chiamata API --> / var xmlhttp = new XMLHttpRequest(); var url = "https://api.coindesk.com/v1/bpi/currentprice.json"; var output; console.log(url); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { output = this.responseText; var obj = JSON.parse(output); var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */ document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue; } }; xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader("Content-type", "text/plain"); xmlhttp.send(); } let price = require('crypto-price'); price.getCryptoPrice('EUR', 'ETH').then(obj => { console.log(obj.price); // It will print ETH rate per BTC document.getElementById("cellaValoreETH").innerHTML = obj.price; }).catch(err => { console.log(err); }); table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table> Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work? How can I add obj.price in my HTML code? Thanks
JS search returned xhr.responseText for div then remove div
I would like to search a xhr.responseText for a div with an id like "something" and then remove all the content from the xhr.responseText contained within that div. Here is my xhr code: function getSource(source) { var url = source[0]; var date = source[1]; /****DEALS WITH CORS****/ var cors_api_host = 'cors-anywhere.herokuapp.com'; var cors_api_url = 'https://' + cors_api_host + '/'; var slice = [].slice; var origin = self.location.protocol + '//' + self.location.host; var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function () { var args = slice.call(arguments); var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]); if (targetOrigin && targetOrigin[0].toLowerCase() !== origin && targetOrigin[1] !== cors_api_host) { args[1] = cors_api_url + args[1]; } return open.apply(this, args); }; /****END DEALS WITH CORS****/ var xhr = new XMLHttpRequest(); xhr.open("GET", cors_api_url+url, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var resp = xhr.responseText; var respWithoutDiv = removeErroneousData(resp); } else{ return "Failed to remove data."; } } xhr.send(); } remove div here: /*This must be in JS not JQUERY, its in a web worker*/ function removeErroneousData(resp) { var removedDivResp = ""; /*pseudo code for removing div*/ if (resp.contains(div with id disclosures){ removedDivResp = resp.removeData(div, 'disclosures'); } return removedDivResp; }
You can dump the response in a div and then search for that div you want empty its content. xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var resp = xhr.responseText; $('div').attr('id', 'resp').html(resp); $('#resp').find('disclosures').html(''); //var respWithoutDiv = removeErroneousData(resp); } else{ return "Failed to remove data."; } }
Not able to view specific information. Click events. Javascript
I've been able to collect a list of companies which are able to be clicked to reveal company data. There are 10 companies total. The problem is, when I click one link to view the data for that specific company, all of the data (for all 10 companies) appear. Here's a picture of my problem. Click here. As you can see, Topsome was clicked, but all the information was shown. Here is the javascript code I'm using. This function (findCompanies.js) collects the list of companies. function findCompanies() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { var companies = JSON.parse(xhttp.responseText); var list = "<p>There are totally "+companies.totalResults+" companies of which the 10 first are listed here.</p>"; for (i=0;i<10;i++) { company = companies.results[i].name; list = list + "<a href='#/' onclick='findCompanyData(company);'>"+company + "</a><br/>"; } document.getElementById("ansver").innerHTML = list; } } url = "http://avoindata.prh.fi:80/tr/v1?totalResults=true&maxResults=10&resultsFrom=0&companyRegistrationFrom="+document.input.start.value+"&companyRegistrationTo="+document.input.end.value; xhttp.open("GET", url, true); xhttp.send(); } This function provides the details of the companies. function findCompanyData(company) { var xhttp2 = new XMLHttpRequest(); xhttp2.onreadystatechange = function() { if (xhttp2.readyState == 4 && xhttp2.status == 200) { var companydata = JSON.parse(xhttp2.responseText); var list = "<h6>Company Information: </h6>"; for (i=0;i<10;i++) { var name = "<p>Company Name: "+companydata.results[i].name +" </p>"; var companyId = "<p>Company ID#: "+companydata.results[i].businessId +" </p>"; var registrationDate = "<p>Registration Date: "+companydata.results[i].registrationDate +" </p>"; var companyType = "<p>Company Type: "+companydata.results[i].companyForm +" </p>"; list = list + name + companyId + registrationDate + companyType; } document.getElementById("companydata").innerHTML = list; } } url = "http://avoindata.prh.fi:80/tr/v1?totalResults=true&maxResults=10&resultsFrom=0&companyRegistrationFrom="+document.input.start.value+"&companyRegistrationTo="+document.input.end.value; xhttp2.open("GET", url, true); xhttp2.send(); } Any advice or recommendations? Thanks in advance!
Try this. function findCompanies() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { var companies = JSON.parse(xhttp.responseText); var list = "<p>There are totally "+companies.totalResults+" companies of which the 10 first are listed here.</p>"; for (i=0;i<10;i++) { company = companies.results[i].name; // Without quotes, 'company' will be treated as a var company = '"'+company+'"'; // ADDED THIS LINE to quote the company list = list + "<a href='#/' onclick='findCompanyData("+company+");'>"+company + "</a><br/>"; } document.getElementById("ansver").innerHTML = list; } } url = "http://avoindata.prh.fi:80/tr/v1?totalResults=true&maxResults=10&resultsFrom=0&companyRegistrationFrom="+document.input.start.value+"&companyRegistrationTo="+document.input.end.value; xhttp.open("GET", url, true); xhttp.send(); } And second function function findCompanyData(company) { var xhttp2 = new XMLHttpRequest(); xhttp2.onreadystatechange = function() { if (xhttp2.readyState == 4 && xhttp2.status == 200) { var companydata = JSON.parse(xhttp2.responseText); var list = "<h6>Company Information: </h6>"; for (i=0;i<10;i++) { // Only add info to be shown if this was the company clicked. if (companydata.results[i].name === company) { // ADDED THIS LINE var name = "<p>Company Name: "+companydata.results[i].name +" </p>"; var companyId = "<p>Company ID#: "+companydata.results[i].businessId +" </p>"; var registrationDate = "<p>Registration Date: "+companydata.results[i].registrationDate +" </p>"; var companyType = "<p>Company Type: "+companydata.results[i].companyForm +" </p>"; list = list + name + companyId + registrationDate + companyType; } } document.getElementById("companydata").innerHTML = list; } } url = "http://avoindata.prh.fi:80/tr/v1?totalResults=true&maxResults=10&resultsFrom=0&companyRegistrationFrom="+document.input.start.value+"&companyRegistrationTo="+document.input.end.value; xhttp2.open("GET", url, true); xhttp2.send(); }