How to get data from a local JSON file in Javascript - javascript

I'm trying to retrieve a specific ID from the JSON file depending on user input and then display a picture based on the ID retrieved from the JSON file
function showCard() {
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj["data"][0]["id"]
document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
event.preventDefault();
}

I think what you need is below but I am not sure I understood your json structure:
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var oReq = new XMLHttpRequest();
oReq.open("GET", "https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper", true);
oReq.responseType = "json";
oReq.onload = function(e) {
JSONObject json = new JSONObject(res);
JSONArray ja = json.getJSONArray("data");
JSONObject obj = ja.getJSONObject(0);
var imgId = obj.id;
document.getElementById("chosenCard").src = "https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jgp";
}
oReq.send();

I tried to answer your problem after identifying your problem.
function showCard()
{
event.preventDefault();
var cardNaqme = document.getElementById('un').value;
var cardNameProper = cardName.replace(/\s/g, '');
var obj = JSON.parse("https://db.ygoprodeck.com/api/v7/cardinfo.php"+cardNameProper)
var imgId = obj[0].id
document.getElementById("chosenCard").src =
"https://storage.googleapis.com/ygoprodeck.com/pics_small/"+imgId+".jpg";
}

Related

Binance Rest API JSON to HTML

I have made 2 .js files with the scripts inside them which are then called by app.html
I'm trying to call both the spot price and 24hr rolling percentage change from Binance rest API. My problem is that it prints the percentage change in the spot pricing HTML element. I think it has something to do with the percentage symbol ID being the same as the spot price symbol ID but I'm not sure.
What did I do wrong?
Here are the finance rest API docs.
HTML
<div class="div-block-3">
<div class="text-block-2"><span class="currency-title">USD</span> <span class="currency-symbol">$</span><strong id="BTCUSDT" class="rates">11,794.00</strong></div>
<div id="BTCUSDT" class="text-block-6"><strong class="negative">-1.84%</strong></div>
</div>
24hr rolling percentage .js
function load() {
var url_base = "https://api.binance.com/api/v3/ticker/24hr?symbol="
var elements = document.getElementsByClassName('text-block-6');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].id;
var url = url_base + id;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url, true);
ourRequest.onload = function () {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
document.getElementById( obj.symbol ).innerHTML = obj.priceChangePercent;
};
ourRequest.send();
}
}
window.onload = load;
spot pricing .js
function load() {
var url_base = "https://api.binance.com/api/v3/ticker/price?symbol="
var elements = document.getElementsByClassName('rates');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].id;
var url = url_base + id;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url, true);
ourRequest.onload = function () {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
document.getElementById( obj.symbol ).innerHTML = obj.price;
};
ourRequest.send();
}
}
window.onload = load;

myObj.forEach(), isn't working

I'm trying store a XMLHttpRequest()'s results as a JSon String in an object, The data in the String is several arrays. I'm trying to then read through each array, in myObj.
Obviously, myObj.forEach() doesn't work, because myObj is an object, not an array or a list. How do I make it so I can itterate through myObj, and then use a forEach on each array?
Here is my current code
function getFile(){
var input = document.getElementsByName("json")[0];
var filename = input.value;
console.log(filename);
var xhr = new XMLHttpRequest();
xhr.open("GET", filename, true);
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var text = xhr.responseText;
document.getElementById("displayText").innerHTML = "";
var myObj = JSON.parse(text);
myObj.forEach(function(student) {...});
}
}
}
You can grab the keys of the Object into a list using Object.keys() and then iterate through them assuming they are all lists:
function getFile(){
var input = document.getElementsByName("json")[0];
var filename = input.value;
console.log(filename);
var xhr = new XMLHttpRequest();
xhr.open("GET", filename, true);
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var text = xhr.responseText;
document.getElementById("displayText").innerHTML = "";
var myObj = JSON.parse(text);
var keys = Object.keys(myObj);
keys.forEach(function(key) {
myObj[key].forEach(function(item) {...})
});
}
}
}

javascript .send() not working on mobile

this javascript is working on desktop but not on mobile browsers. Is there an edit which could resolve this?
The script send the results to a questionnaire to a google document to pull out the results. It works ok on a desktop browser but no luck on mobiles.
<script>
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function(evt) {
evt.preventDefault();
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbzGx6a6eogfVTaKD_3a4kiLBZfcdD5GMoonNsSSY1-sCCJfPDI/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = response.result;
for (var i in result) {
var e = result[i];
if (e) {
var li = document.createElement('li');
if (e.url) {
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.name;
li.appendChild(a);
} else {
li.textContent = e.name;
}
resultList.appendChild(li);
}
}
busyDiv.hidden = true;
resultDiv.hidden = false;
}
}
var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','income','asset','q1','q2','q3','q4','q5','q6','q7','q8','q9','q10'];
var params = [];
for (var i in fields) {
var field = fields[i];
params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));
questionDiv.hidden=true;
busyDiv.hidden=false;
return false;
};
}
</script>

Is there a way to edit this script to overwrite a csv on the server rather than download locally?

I am attempting to use tabletoCSV.js to allow a client to edit their prices in an editable html table and export the changes to overwrite the existing csv file.
jQuery.fn.tableToCSV = function() {
var clean_text = function(text){
text = text.replace(/"/g, '""');
return '"'+text+'"';
};
$(this).each(function(){
var table = $(this);
var caption = $(this).find('caption').text();
var title = [];
var rows = [];
$(this).find('tr').each(function(){
var data = [];
$(this).find('th').each(function(){
var text = clean_text($(this).text());
title.push(text);
});
$(this).find('td').each(function(){
var text = clean_text($(this).text());
data.push(text);
});
data = data.join(",");
rows.push(data);
});
title = title.join(",");
rows = rows.join("\n");
var csv = title + rows;
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
var download_link = document.createElement('a');
download_link.href = uri;
var ts = new Date().getTime();
if(caption==""){
download_link.download = ts+".csv";
} else {
download_link.download = caption+"-"+ts+".csv";
}
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
});
};
As of right now, it simply downloads a generic csv file. Assume the name of the file is "menu.csv".

Change the reply email address to the queue's email address in dynamic crm 2011

What i want to do is when we click on Reply button , the From address field will be populate with the email-id (default team's default queue's email-id). Current scenario is populated with logged in user.
I used the following js code onLoad, but I am getting an error that says "Object doesn't support property or method getAttributeValue
function CheckEnquiryReplyAddress() {
// Only complete this validate on Create Form
var formType = Xrm.Page.ui.getFormType();
var emailStatus = Xrm.Page.getAttributeValue("statecode").getValue();
var emailDirection = Xrm.Page.getAttributeValue("directioncode").getValue();
if (formType == 1 || (formType == 2 && emailStatus == "Open")) {
if (emailDirection == "1"){
var previousEmailId=getExtraqsParam("_InReplyToId", window.parent.location.search);
//getting context from the parent window
var context = Xrm.Page.context;
try {
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var query="/EmailSet?$select=ActivityId,ActivityTypeCode,DirectionCode,";
query=query+"ToRecipients,Email_QueueItem/QueueId&$expand=Email_QueueItem&$filter=ActivityId eq guid'" + previousEmailId +"'";
query =serverUrl+ODATA_ENDPOINT+ query;
var request= new XMLHttpRequest();
request.open("GET", query, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.onreadystatechange=function(){ CompleteEnquiryReplyCheck(request,serverUrl);}
request.send(null);
}
catch(e) {
alert(e.Description);
}
}
}
}
function CompleteEnquiryReplyCheck(request,url)
{
if (request.readyState==4) {
if(request.status==200) {
var queue=JSON.parse(request.responseText).d.results[0];
if (queue != null) {
var queueId = queue.Email_QueueItem.results[0].QueueId.Id;
var lookup = new Array();
var lookupItem = new Object();
lookupItem.id = queueId;
lookupItem.name = queue.Email_QueueItem.results[0].QueueId.Name;
lookupItem.typename = "queue";
lookup[0] = lookupItem;
Xrm.Page.getAttribute("from").setValue(lookup);
}
}
}
}
The get attribute value method is incorrect, to get value of an attribute use the following:
var attributeValue = Xrm.Page.getAttribute("attributeName").getValue();
So, in your case it would be:
var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();

Categories