Trying to Display API Data in HTML - javascript

I am trying to make an API call and display that data on my HTML page. Currently no data is displayed when the button is clicked, but the API call is made successfully as I can track my usage on another page. My code is below:
<!DOCTYPE html>
<html>
<body>
<h1>API Data</h1>
<div id="container">
<div id="api">Nothing Yet</div>
</div>
<br>
<button type="button" onclick="loadAPI()">Change Content</button>
<script>
function loadAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "API URL with Token here", false);
xhttp.addEventListener("load", loadData);
xhttp.send();
}
function loadData() {
document.getElementById('api').innerText = JSON.parse(this.responseText);
}
</script>
</body>
</html>

No data is displayed because you're not putting the data into the target element.
To insert data into #api, you need to do something like
document.getElementById('api').innerHTML = apiResponse; // no underscore
// or
document.getElementById('api').innerText = apiResponse;
I'll leave it for you to read up on security. https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Also, XMLHttpRequest is asynchronous unless specified otherwise (in a param). So the most reliable way is to display the data in the load event listener. Your final code should be something like:
// Making a XMLHttpRequest
function loadAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "API URL with Token Here", false);
xhttp.addEventListener("load", loadData);
xhttp.send();
}
// Displaying the data
function loadData() {
document.getElementById('api').innerText = this.responseText;
}
Note if your response is in JSON, you need to JSON.parse(this.responseText) to access the array/objects.

Related

HTML- How can I insert the contents of a .txt file into a variable to use .innerHTML to change the contents of <body>?

Im trying to create an automated system for HTML page handling where I will be able to change the contents
of a<div> inside <body> by writing into an external .txt file and uploading it to the server. Im still an early student in university
and I havent learned PHP and JQuery yet. So I am trying to accomplish this by using only Javascript and HTML.
I just need a way for whatever I write inside the .txt file to be written again inside the <div class="CONTENT" id="target"> which is inside the <body> automatically. Any thoughts and suggestions are greatly appreciated!
You can solve your problem by using the FileReader.
Have a look to
this answer.
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('target');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<html>
<head></head>
<body>
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<div id="target" class="CONTENT"></div>
</body>
</html>
You can make an AJAX call for the text file and take the response from that call and set that as the .textContent of the div. Here's an example (see comments inline):
const output = document.getElementById("output");
// Create XHR object
var xhr = new XMLHttpRequest();
// Configure the request (substitute a URL
// to the file below)
xhr.open("GET", filePathHere, false);
// Set up the callback for when the response has
// been recieved
xhr.onreadystatechange = function (){
if(xhr.readyState === 4) {
// Was the request successful?
if(xhr.status === 200 || xhr.status == 0) {
// Populate the <div> with the response text
output.textContent = xhr.responseText;
}
}
}
xhr.send(null); // Make the call
<div id="output"></div>

Javascript output sent to PHP for adding into database

I have wrote a HTML/Javascript code generator but instead of outputting the code to a HTML site i would like the code to be send to php to be added to a database but i cant work out how to get the out put of the javascript into PHP
there is also another javascript doc to go with this if you need it to make it work ..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../voucher_codes.js"></script>
</head>
<body>
<h1>pattern codes</h1>
<ul id="pattern-codes"></ul>
<script>
var patternCodes = voucher_codes.generate({
prefix: "BREAK-",
postfix: "-2019",
length:5,
count: 5,
charset: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
});
function fillList(listId, items) {
var list = document.getElementById(listId);
items.forEach(function(item) {
list.innerHTML += "<li>" + item + "</li>";
});
}
fillList("pattern-codes", patternCodes);
</script>
</body>
</html>
i am wanting the output of the function "fillList" to send the output to PHP if this is possible....
You would have to look into using AJAX or the Axios library to send requests to a server page such as PHP.
Here is a simple AJAX POST server request in Javascript:
`
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
}
};
xhttp.open("POST", "request_page.php", true); // set method and page
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set content type that we are sending POST data
xhttp.send("key=VALUE&key=VALUE"); // POST values
}
</script>
`
On the PHP page if you want to give a response of data to use back in Javascript, make sure to
json_encode($array_values)
the data array before echoing it out and set the headers to
header("Content-Type: application/json")
so you can grab the response data in Javascript and it can be turned into a Javascript {Object} or [Array]

How to display an html file in javascript?

I am trying to display an html file in my js-code.
It is an ordinary html file that I would like to see. I have already created an IFRAME for this, but somehow I cannot go further...
This is my code fragment:
var controlAddIn = document.getElementById('controlAddIn').src = 'index.html';
So the file I want to call is "index.html". But it is not working.
If I call it in that way:
var controlAddIn = document.getElementById('controlAddIn').srcdoc = '<div><meta charset="UFT-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></div>';
It is working, but taht makes it very hard to read...
Do you have an idea, how I can call my entire code at this point, also multiline?
The both file should be same path if you are calling like that
else you have call the correct path
var controlAddIn = document.getElementById('controlAddIn').src = 'index.html';
save this file in index.html path and open it on browser
<script type="text/javascript">
function newSite() {
document.getElementById('myIframe').src = "index.html"
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://google.com/" ></iframe>
You Could use XMLHttp request to get Html File Content this code async
function httpGet(theUrl,callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, true ); // false for synchronous request
xmlHttp.send( null );
xmlHttp.onreadystatechange = function() {
callback(xmlHttp.responseText);
};
}
var controlAddIn;
httpGet("index.html",function(content){
controlAddIn = document.getElementById('controlAddIn').src =content;
});

Sending a Request To a database(google sheets)

I have created a script within google sheets. It gives a result of a cell from my table in google sheets(kinda database). I want the result send to my html page, and i have tried so far with XMLHttprequest but with no success.
What have i done wrong?
Here is the Script
<script>
function load() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://script.google.com/macros/s/AKfycby5RzvUWSEOjerJpouxN72wpsgpsF8IWQo2AvjZUdRPcqskz28/exec", true);
xhttp.send();
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="load()">Request data</button>
<p id="demo"></p>
</body>
</html>
To read a spreadsheet from google:
download a script called Tabletop and add it to your HTML. (The readme is here)
In Google Docs go up to the File menu and pick Publish to the web. Then click Start publishing. A URL will appear, something like https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html, that is the URL you will use.
Then call it with this:
<script type="text/javascript">
var public_spreadshseet_url = 'https://docs.google.com/spreadsheet/pub?YOUR_URL_HERE';
// YOUR_URL_HERE sample: hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html
// You get this URL from google docs after you publish the spreadsheet
function init()
{
Tabletop.init(
{
key: public_spreadshseet_url,
callback: showInfo,
simpleSheet: true
})
}
// This function gets called to give output
function showInfo(data)
{
alert("Successfully processed!")
console.log(data); <-- Here is the spreadsheet data
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="init()">Request data</button>
<p id="demo"></p>
</body>
</html>

How to call a REST web service API from JavaScript?

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch() method. It takes two arguments:
A URL or an object representing the request.
Optional init object containing the method, headers, body etc.
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Your Javascript:
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Your Button action::
<button type="submit" onclick="UserAction()">Search</button>
For more info go through the following link (Updated 2017/01/11)
Here is another Javascript REST API Call with authentication using json:
<script type="text/javascript" language="javascript">
function send()
{
var urlvariable;
urlvariable = "text";
var ItemJSON;
ItemJSON = '[ { "Id": 1, "ProductID": "1", "Quantity": 1, }, { "Id": 1, "ProductID": "2", "Quantity": 2, }]';
URL = "https://testrestapi.com/additems?var=" + urlvariable; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
I think add if (this.readyState == 4 && this.status == 200) to wait is better:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("GET", "your url", true);
xhttp.send();
If that helps anyone, if you are ok with an external library then I can vouch for Axios, which has a pretty clean API and rich documentation to deal with REST calls, here's an example below:-
const axios = require('axios');
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
});
Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.
We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
// Begin accessing JSON data here
}
}
// Send request
request.send()
By far, the easiest for me is Axios. You can download the node module or use the CDN for your simpler projects.
CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Code example for GET/POST:
let postData ={key: "some value"}
axios.get(url).then(response =>{
//Do stuff with the response.
})
axios.post(url, postData).then(response=>{
//Do stuff with the response.
});
Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method. Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript. Here is an example that assumes the REST API is in file REST.php:
<body>
<h2>REST-test</h2>
<input type=button onclick="document.getElementById('a').submit();"
value="Do It">
<form id=a action="REST.php" method=post>
<input type=hidden name="arg" value="val">
</form>
</body>
Note that this example will replace the page with the output from page REST.php.
I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page. But it's certainly simple.
Usual way is to go with PHP and ajax. But for your requirement, below will work fine.
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>

Categories