Javascript check if an html file exists [duplicate] - javascript

This question already has answers here:
using javascript to detect whether the url exists before display in iframe
(8 answers)
Closed 5 years ago.
How can I check if there is an .html file in a folder exists? I'm trying to not get the error "It may have been moved or deleted." and instead display notFound.html
<body>
<header>
<form autocomplete="off">
<input id="3Digits" type="number" min="100" placeholder="3-Digit Code">
<span style="display:inline-block; width: 15px;"></span>
Go
<hr>
</form>
</header>
<div id="frameDiv">
<iframe id="srcCC"></iframe>
</div>
<script>
var newLink
function check() {
newLink = document.getElementById("3Digits").value + ".html";
if(newLink == ".html") {
alert("You forgot to put the 3-Digit Code");
}
else {
LinkCheck(newLink);
}
}
function LinkCheck(url) {
if(HTML EXISTS) {
document.getElementById("frameSRC").src = newLink;
}
else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
</script>
</body>
The function LinkCheck is what I'm asking for, all the files are going to be in the same directory.
This is a small school project, so any help would be appreciated!

You can use XMLHttpRequest to check if the file exists
function LinkCheck(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}

Replace your function with this:
function LinkCheck(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.getElementById("frameSRC").src = newLink;
} else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
};
xhr.send(null);
}
Option 2: use jQuery ajax
function LinkCheck(url) {
$.ajax({
url: url,
success: function(data) {
document.getElementById("frameSRC").src = newLink;
},
error: function(data) {
document.getElementById("frameSRC").src = "notFound.html";
},
})
}

Try replacing your function LinkCheck with this:
function LinkCheck(url) {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) { // if (HTML EXISTS)
document.getElementById("frameSRC").src = newLink;
} else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
http.open('get', url, true);
http.send();
}
If that says some deprecation issue try the new javascript native fetch API:
function LinkCheck(url) {
fetch(url).then(function(response) {
if (response.status === 200) {
document.getElementById("frameSRC").src = newLink;
} else {
// this else isn't needed but you can put it here or in the catch block
document.getElementById("frameSRC").src = "notFound.html";
}
})
.catch(function (err) {
throw err;
});
}

Related

Blogger feed posts showing CORS Error on different site

With reference to this answer of Google, I tried to use the json version of my feeds by using the URL: https://[blog address].blogspot.com/feeds/posts/default?alt=json. My blog is set to public mode, but then also it is throwing CORS policy. And this is the code I used:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON('https://[blog].blogspot.com/feeds/posts/default?alt=json',
function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
alert('Your query count: ' + data.query.count);
}
});
</script>
Try alt=json-in-script instead:
<script type="text/javascript">
function myFunction({feed}) {
alert('Your query count: ' + feed.entry.length);
}
</script>
<script type="text/javascript" src="https://blog.blogspot.com/feeds/posts/default?alt=json-in-script&callback=myFunction"></script>

Windows Location don't redirect after XMLHttpRequest

I have these code with a XMLHttpRequest:
function Registrarse()
{
conexionRegistrarse = new XMLHttpRequest();
conexionRegistrarse.onreadystatechange = procesarRegistro;
conexionRegistrarse.open('GET', 'index.php?registrarse=&username='+username+'&mail='+mail+'&pw='+contraseña+'&pwr='+repetircontraseña, true);
conexionRegistrarse.send();
}
function procesarRegistro()
{
var detalles = document.getElementById("labelUsername");
if(conexionRegistrarse.readyState == 4)
{
if((conexionRegistrarse.responseText).indexOf("cuenta") == -1)
{
window.location = "http://localhost/index.php?creada";
}
else
{
detalles.innerHTML = conexionRegistrarse.responseText;
}
}
else
{
detalles.innerHTML = "Cargando...";
}
}
The problem is that when a succesfull register happen (these occurs when the responseText of the xmlhttprequest don't have the string "cuenta"), don't redirect me to: "index.php?creada". I try with assign() and neither work.
I tested.
It works very well.
code As:
var oAjax = new XMLHttpRequest();
oAjax.open('GET', 'a', true);
oAjax.send();
oAjax.onload = function() {
if (oAjax.status == 200) {
window.location = 'http://baidu.com';
}
};
as well, check your error message!

Loader div doesn't appears [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the code below and my div with loader gif doesn't appears. I tried many ways to do that and I could. Why $('.loader').show(); doesn't works?
$('.loader').show();
var url = "myURL.ashx?p1=" + p1;
if (GetRequestReturnStatus(url)) {
window.open(url);
}
$('.loader').hide();
function GetRequestReturnStatus(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
if (http.status == 404 || http.status == 403 || http.status == 500) {
ShowMessage("nFailure", "some message");
return false;
}
return true;
}
And the HTML:
<div class="loader" style="display: none;">
<asp:Image ID="Loader" CssClass="p12" ImageUrl="~/_img/loader.gif" runat="server" ViewStateMode="Enabled" />
</div>
It's working in another functions in the code. Just in that case doesn't works.
I'm not using ajax because I don't know how to download de response and when I was looking for that topic, I read is better use window.open than ajax to download file.
It is working, however you are immediately hiding it again with $('.loader').hide();
$('.loader').show();
var url = "myURL.ashx?p1=" + p1;
if (GetRequestReturnStatus(url)) {
window.open(url);
}
//$('.loader').hide(); //this line was hiding your .loader element(s)
function GetRequestReturnStatus(url) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
//todo logic here once the request has changed state
if(http.readyState == 4) { //done loading
hideLoader();
}
};
http.open('HEAD', url, false);
http.send();
if (http.status == 404 || http.status == 403 || http.status == 500) {
ShowMessage("nFailure", "some message");
return false;
}
return true;
}
function hideLoader() {
$('.loader').hide();
}
You can see it in this JS fiddle: https://jsfiddle.net/jr5uye4o/2/
There is more reading on how to use XMLHttpRequest here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Since you are already using jQuery, why not use $.ajax for the request?
$.ajax({
method: "GET",
url: "/yourRequestUrl",
data: { p1: yourParam, p2: otherParam }
}).done(function(msg) {
$('.loader').hide(); // Processed once the request is complete.
})
.fail(function() {
alert("Something went wrong with the request");
});

How to retrieve an element from an ajax call

I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}

Simple AJAX example - load data from txt file

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.
<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
function ajaxCallback(event){
alert( "Your file contains the text: " + event.target.responseText );
}
</script>
</head>
<body>
</body>
</html>
here is a function i always use for simple async get ajax:
1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.
2.don't do syncronous ajax.
js
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
example
http://jsfiddle.net/9pCxp/
extra info
https://stackoverflow.com/a/18309057/2450730
full html
<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
Here is your answer.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var allText = this.responseText;
alert(allText);
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
The below code may be useful for someone...
<!DOCTYPE html>
<html>
<body>
<h1>Load Data from text file </h1>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info.txt", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)
Paste this code between "head" tags.
<script>
var xmlhttp;
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc("hello.xml", function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
As you see, javascript is referring to "hello.xml" file to get information from.
Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"
Paste this code to your XML file.
<?xml version="1.0" encoding="utf-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Run your php (or .aspx) file on localhost.
Click on button, your page must acquire the XML data into your website.
function Go() {
this.method = "GET";
this.url = "hello.txt";
if (window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
this.xmlhttp = new XMLHttpRequest();
}
catch (e) {
this.xmlhttp = false;
}
// branch for IE/Windows ActiveX version
}
else if (window.ActiveXObject) {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
this.xmlhttp = false;
}
}
}
if (this.xmlhttp) {
var self = this;
if (this.method == "POST") {
this.xmlhttp.open("POST", this.url, true);
}
else {
//remember - we have to do a GET here to retrive the txt file contents
this.xmlhttp.open("GET", this.url, true);
}
this.xmlhttp.send(null);
//wait for a response
this.xmlhttp.onreadystatechange = function () {
try {
if (self.xmlhttp.readyState == 4) {
if (self.xmlhttp.status == 200) {
if (self.xmlhttp.responseText != null) {
self.response = self.xmlhttp.responseText;
alert(self.xmlhttp.responseText);
}
else {
self.response = "";
}
}
else if (self.xmlhttp.status == 404) {
alert("Error occured. Status 404: Web resource not found.");
}
else if (self.xmlhttp.status == 500) {
self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
}
else {
alert("Unknown error occured. Status: " + self.xmlhttp.status);
}
}
}
catch (e) {
alert("Error occured. " + e.Description + ". Retry or Refresh the page");
}
finally {
}
};
}
}
//Use the function in your HTML page like this:
Go();
</script>

Categories

Resources