if-URL-exists check with javascript - javascript

I'm trying to create an if-file-exists check on a URL.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else xhr = null;
return xhr;
}
function UrlExists(url) {
var http = createCORSRequest('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
if (this.status == 404) {
alert(url + " is NOT available!");
} else if (this.status != 0) {
alert(url + " is available!");
}
}
};
http.send();
}
UrlExists("http://bar.baz");
UrlExists("http://google.com");
</script>
Testing URLs
</body>
</html>
Currently getting a XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. error -- even when its running through Apache HTTPd on Mac OS 10.9.
Can you all help me to get this to work?

This is a cross origin issue.
You have to use proxy.
For example, I've used YQL.
Try the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");

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>

How to send AJAX post request and receive back JSON data in Vanilla JS?

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}

Javascript check if an html file exists [duplicate]

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

Ajax request response null

Ajax request is successful but response is null but I can see the result response in firebug as:
<?xml version="1.0" encoding="UTF-8" ?><response><likes>13</likes></response>
And in the console there is error as :
TypeError : response is null
var XMLHttpObject = createXMLHttpRequest();
$Id = null;
function process(id) { //makeAsynchornusRequest
if(XMLHttpObject.readyState == 0 || XMLHttpObject.readyState == 4) {
XMLHttpObject.onreadystatechange = responseHandler;
$Id = id;
XMLHttpObject.open("GET","like/" + id);
XMLHttpObject.send(null);
}
}
function responseHandler() {
if(XMLHttpObject.readyState == 4) {
if(XMLHttpObject.status == 200) { // 200 implies `ok` like 400 implies `page not found`
response = XMLHttpObject.responseXML;
xmlDocumentElement = response.documentElement;
output = document.getElementById("num_likes" + $Id);
output.innerHTML = xmlDocumentElement ;
}
}
}
You have tagged JQuery - try using JQuery for your Ajax call:
$.ajax({
url: '/Likes',
data: { id: id },
success: function (response) {
if (response) {
console.log(response);
}
},
error: function (xhr, s, sa) {
console.log(s, sa);
},
complete: function () {
console.log('complete event');
}
});
Can you try switching this to an onLoad event handler.
From mozilla docs:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log(xhr.responseXML);
}
}
};
xhr.send(null);
With your code (note you may need to tweak the responseHandler() body slightly:
XMLHttpObject.open("GET","like/" + id);
xhr.onload = responseHandler;
XMLHttpObject.send(null);

Detect browser tab close without jquery and send some data to php file

I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload

Categories

Resources