Https reqest to get Gift card balance with JavaScript - 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.

Related

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

JavaScript - Self-invoking function can't see functions from external script

I have a conceptual issue about scopes on the following code.
The code is a simple client-side validation script for two forms.
I used a self-invoking function to try a something different approach by avoiding to set all global variables but its behavior seems a bit weird to me.
I am still learning to code with JavaScript and I'm not an expert, but these advanced features are a bit complicated.
I don't want to use jQuery but only pure JavaScript in order to learn the basis.
<!-- Forms handling -->
<script src="validate_functions.js"></script>
<script>
(function main() {
var frmPrev = document.getElementById('frmPrev');
var frmCont = document.getElementById('frmCont');
var btnPrev = frmPrev['btnPrev'];
var btnCont = frmCont['btnCont'];
var caller = '';
var forename = '';
var surname = '';
var phone = '';
var email = '';
var privacy = '';
var message = '';
var infoBox = document.getElementById('info-box');
var infoBoxClose = infoBox.getElementsByTagName('div')['btnClose'];
btnPrev.onclick = function(e) {
submit(e);
};
btnCont.onclick = function(e) {
submit(e);
};
function submit(which) {
caller = which.target.name;
var errors = '';
if(caller == 'btnPrev') {
forename = frmPrev['name'].value.trim();
surname = frmPrev['surname'].value.trim();
phone = frmPrev['phone'].value.trim();
email = frmPrev['email'].value.trim();
message = frmPrev['message'].value.trim();
privacy = frmPrev['privacy'].checked;
}
if(caller == 'btnCont') {
phone = frmCont['phone'].value.trim();
email = frmCont['email'].value.trim();
message = frmCont['message'].value.trim();
}
errors = validateFields(caller, forename, surname, phone, email, privacy, message);
if(errors == '') {
var params = 'which=' + caller;
params += '&fname=' + forename;
params += '&sname=' + surname;
params += '&tel=' + phone;
params += '&email=' + email;
params += '&priv=' + privacy;
params += '&mess=' + message;
var request = asyncRequest();
request.open('POST', "send-mail.php", true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Content-length', params.length);
request.setRequestHeader('Connection', 'close');
request.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
if(this.responseText != null) {
infoBox.innerHTML = this.responseText;
} else {
infoBox.innerHTML = '<p>No data from server!</p>';
}
} else {
infoBox.innerHTML = '<p>Could not connect to server! (error: ' + this.statusText + ' )</p>';
}
}
}
request.send(params);
} else {
infoBox.innerHTML = errors;
}
infoBox.style.display = 'block';
}
infoBoxClose.onclick = function() {
infoBox.style.display = 'none';
infoBox.innerHTML = '';
};
function validateFields(_caller, _forename, _surname, _phone, _email, _privacy, _message) {
var errs = '';
if(_caller == 'btnPrev') {
errs += validateForename(_forename);
errs += validateSurname(_surname);
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
errs += validatePrivacy(_privacy);
}
if(_caller == "btnCont") {
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
}
return errs;
}
function asyncRequest() {
var request;
try {
request = new XMLHttpRequest();
}
catch(e1) {
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e3) {
request = null;
}
}
}
return request;
}
})();
Web console keeps telling me that single validate functions are not defined.
Why?
They should be loaded from the external script.. furthermore they should have a global scope.
Thank you in advance :)
Problem solved!
The path to the external script was incorrect.
Sorry for this rubbish! ^^"

JavaScript - Calling an 'onClick' function from a For loop loading multiple links

I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below code?
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 += arr[i].timetable_1_link;
URL_2 += arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can start by refactoring the function that opens the URL to accept a parameter like this:
function openLinkInNewWindow_1(URL) {
window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
Then in the for loop pass the URL along with each link.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
This way you only need the one function. Notice also that I removed the + from the URL_1 += line.
Using URL_1+= is culprit here. Every time loops run it appends new string to existing url(s).
So remove += from URL_ variables in your function 'myFunction' and assign values directly by using '=' only.
Updated code is written below
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can take a look for updated and running code here

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();
}

Categories