Check if url is working and if so do something - javascript

I found the following solution Checking if a URL is broken in Javascript
In the answer it says to use
checkLink = async url => (await fetch(url)).ok
to check if a url is available.
So let's assume I would like to display a message in case a url is working so I wrote:
let url = 'https://www.example.com/index.html';
if(checkLink = async url => (await fetch(url)).ok) {alert ("Hello world!");};
Unfortunately the above code always shows the alert message no matter if the url is available or not.
How can I use this code to test if a url is valid.

With the function definition you gave
checkLink = async url => (await fetch(url)).ok
you would typically use this as follows.
async function doStuff() {
let url = 'https://www.example.com/index.html';
let doesLinkWork = await checkLink(url);
if (doesLinkWork) {
alert("it works");
} else {
alert("it doesn't work");
}
}
and then call doStuff from the console or from somewhere else in your code. (Obviously that function name is just an example - you should call it something more appropriate to what you actually want it to do!)

If you are looking to use an input field or something of the sorts, you can use checkValidity().
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity
<html>
<body>
<script>
function validation() {
const inp = document.getElementById("url");
const p = document.getElementById("text");
if(!inp.checkValidity()){
p.innerText = inp.validationMessage;
}
}
</script>
<form>
<input id="url" type="url" placeholder="URL Here">
<input type="submit" value="Submit" onclick="validation()">
</form>
<p id="text"></p>
</body>
</html>

Related

XMLHttpRequest and Fetch not functioning

So I am working on my first project that uses JavaScript with HTML, its a basic weather webpage. The user inputs their location and it displays the current weather. Got the HTML working smoothly but the JavaScript keeps stuffing up. The weird part is that there are no errors in the console so it should be working just fine.
Here is the part of the HTML:
<section id="weather">
<div id="nav">
<div id="locate">
<div id="container">
<form id="location-form">
<label for="location">Location (eg. London,uk):</label>
<input type="text" id="location" name="location" required>
<button type="submit" form="location-form" formnovalidate>Let's Go!</button>
</form>
</div>
</div>
<div id="weather-output">
<!-- Output of API goes here -->
</div>
</div>
</section>
Here is my JavaScript. I have embedded it using script tags because it wasn't detecting button presses.
<script type="text/JavaScript">
function fetchAPIData() {
const locationInput = document.getElementById("location");
const locationValue = locationInput.value;
const url = `http://api.openweathermap.org/data/2.5/weather?q=${locationValue}&APPID=API_URL`;
// do the URL Request
async function xmlrequest() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("weather-output").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
xmlrequest();
}
//listens for button on html side and runs fetchAPIData()
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("button[type=submit]").addEventListener("click", fetchAPIData);
}
);
</script>
I have tried it with both XMLHttpRequest (shown above) and Fetch. Neither work, they do not function nor displayed errors. I am using OpenWeatherMap I have an API key and it works as a plain url but when it the script it doesn't. Any help would be amazing!
mrt
Edit: Firebase analytics is working, its status code is '200'.
There are not any status codes nor error messages for the API though. Updated the code now there is an error '400' so it still doesn't work but I can troubleshoot it now. Thanks everyone for you help!
Solution 1
The problem is that you wrote type of button as "submit":
<button type="submit" form="location-form" formnovalidate>Let's Go!</button>
Try type="button":
<button type="button" form="location-form" formnovalidate>Let's Go!</button>
and amend js:
document.querySelector("button[type=button]").addEventListener("click", fetchAPIData);
Solution 2
use e.preventDefault() function:
function fetchAPIData(e) {
e.preventDefault();
const locationInput = document.getElementById("location");
const locationValue = locationInput.value;
.....
In addition to what James wrote fetch with async/await should still be the way forward here.
A basic (contrived) example:
// Make this function async
async function fetchAPIData() {
// Get the value from your input
const { value } = locationInput;
const endpoint = `http://api.openweathermap.org/data/2.5/weather?q=${value}&APPID=API_URL`;
// Await the response
const response = await fetch(endpoint);
// If it's ok parse the data and update the DOM
// otherwise throw an error
if (response.ok) {
const data = await response.json();
output.innerHTML = data;
} else {
throw new Error('Bad response');
}
}

Output html element content in another innerHTML js

I want to create a dynamic URL. The domain part should remain the same. For example: In this URL "https://www.google.com/search?", I want to append content fetched from another website.
I use this js to fetch and store result to Html element "KK1"
<script>
'use strict';
(async () => {
let response = await fetch('https://api.com/values/1');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
})()
</script>
Assuming the response received from fetch is amoeba1, I want to generate a URL like "https://www.google.com/search?amoeba1"
My code
<!DOCTYPE html>
<html>
<head><script>
'use strict';
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
})()
</script>
<title>My title Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ "I ADD WHAT HERE TO??";
</script>
BELOW IS THE STRING I WANT TO APPEND.
<p id="KK1"></p>
</body>
</html>
How do I append the fetched string? The string is already in
<p id="KK1"></p>
Looking Forward to getting help.
You are looking for anchor tag & you want to add dynamic href:
<!DOCTYPE html>
<html>
<head><script>
'use strict';
var res = "";
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ text;
document.getElementById("demo").href = "https://www.google.com/search?"+ encodeURI(text);
})()
</script>
<title>My title Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<a id="demo"></a><br>
BELOW IS THE STRING I WANT TO APPEND.
<p id="KK1"></p>
</body>
</html>
document.getElementById("demo").innerHTML = "https://www.google.com/search?" + document.getElementById("KK1").innerHTML
Maybe you can modify your script to store in a variable the text result from your API call then with template literals, using ${} you can build your new string for demo element.
Like the following
const resultText = text.slice(0, 80);
document.getElementById("KK1").innerHTML = resultText;
document.getElementById("demo").innerHTML = `https://www.google.com/search?${resultText}`;
Or there are other ways to concatenate a string like:
'https://www.google.com/search?' + resultText
Read further here: Template literals (Template strings)
Update:
So you need to merge those two <script> tags what you have.
I guess this will do that job for you:
'use strict';
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
// essential modified part:
const resultText = text.slice(0, 80);
document.getElementById("KK1").innerHTML = resultText;
document.getElementById("demo").innerHTML = `https://www.google.com/search?${resultText}`;
})();
And don't forget to remove this one:
<script>
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ "I ADD WHAT HERE TO??";
</script>
I hope that helps!

how to make an Ajax request to a URL and append the url with query string in order to run the url program

I am trying to get information from a form without using a submit button. First I need to build a query string and then I need to make an ajax request to a URL that contains a program that will take the information from the forms to calculate the mileage from one city to the other. here is my http file:
<!DOCTYPE html>
<html>
<head>
<title>Mileage Calculator</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<h1>Mileage Calculator</h1>
<form>
Start City<input type="text" id="startCity" name="startCity"></input><br><br>
Start State<input type="text" id="startState" name="startState"></input><br><br>
End City<input type="text" id="endCity" name="endCity"></input><br><br>
End State<input type="text" id="endState" name="endState"></input><br><br>
<input type="button" onclick="buildQuery()" value="Submit"></input>
</form>
<p id="justTry">Let's see if we can change this guy</p>
<script src="assign12.js"></script>
</body>
</html>
I am using an onclick event to call a javascript function that collects all the form info and arranges it into a query string. Here is that function "buildQuery()" :
function buildQuery() {
startcity = document.getElementById("startCity").value;
startstate = document.getElementById("startState").value;
endcity = document.getElementById("endCity").value;
endstate = document.getElementById("endState").value;
var params = {
startcity,
startstate,
endcity,
endstate
};
var esc = encodeURIComponent;
var query = Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
loadSite(query);
}
the buildQuery() function then calls the loadQuery(query) function which makes an ajax request. This is were I am having trouble. the query string must be appended to the URL so it can take the form info and calculate the mileage, but I'm not sure how to get that to happen. here is what I have so far:
function loadSite(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
appendQuery(this.responseText);
//document.getElementById("justTry").innerHTML = url;
}
};
var url = "/cgi-bin/ercanbracks/mileage/mileageAjaxJSON" + query;
xhttp.open("POST", "/cgi-bin/ercanbracks/mileage/mileageAjaxJSON", true)
xhttp.send();
}
what is the best way to accomplish this task?
thanks, Megan
First thing first, you should not manually select all the inputs with ids. Instead I would recommend selecting the inputs using querySelectorAll as below
function getFormPayload(formId){
const payload = {};
for(const input of document.querySelectorAll(`form#${formId} *[name]`)){
payload[input.getAttribute('name')] = input.value;
}
return payload;
}
With the function above you can then iterate through the value and create the query as you initially did.
p/s: Note that some elements like select doesn't have value attribute so you would need to wrap the value assign in an if statement. Good luck!

How to render HTML file using JavaScript [duplicate]

I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>

Generating File object that can be read by javascript FileReader without HTML Input tag

I'm a newbie to dynamic HTML websites so bear with me. This is a locally run webpage for my network only. On load of my webpage, I want it to read a text file and place the data into a textarea. This will then update every couple seconds to display the changes in the text file. I've read several examples on how to do it using the input tag in HTML, but I want it to load without user input.
I'd like to use FileReader() with javascript, but don't know how to make an object that can be read by readAsText(object_here).
<script>
var intervalID1;
function updateTextTimer()
{
intervalID1 = setInterval(updateText,5000);
}
function updateText()
{
var temp = document.getElementById('logOutput');
var reader = new FileReader();
var fileName = "test.txt";
reader.onload = function(e) {temp.value = e.target.result;}
reader.readAsText(file_object);
}
</script>
Again, I'd prefer to use FileReader because it would be easy, but willing to take suggestions. Thanks!
Try using .load()
var timeout = null;
(function loadText() {
$("#logOutput").load("test.txt", function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(loadText, 5000)
})
}())
e.g.,
var timeout = null, obj = null;
(function loadText() {
obj = URL.createObjectURL(new Blob([$("#input").val()], {
type: "text/plain"
}))
$("#logOutput").load(obj, function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(loadText, 5000)
})
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<label for="input">input text here:</label><br />
<textarea id="input">
</textarea>
<br />
<label for="logOutput">output:</label>
<br />
<textarea id="logOutput" disabled>
</textarea>
readAsText Only accept Blob object, you can ref how to create a Blob OBj.

Categories

Resources