Blogger feed posts showing CORS Error on different site - javascript

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>

Related

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

HTML5 java script XMLHttpRequest status 0 and responseText is empty

I am trying to call web service in html5 javascript. But XMLHttpRequest status value getting ZERO insted of 200 and responseText is empty. help me to solve the issue, My code below
<script type="text/javascript">
var xhr;
function Getdet()
{
try {
xhr = new XMLHttpRequest();
xhr.open('POST', "URL", true); // URL-->Webservice link
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.responseType = 'json';
}
catch(err)
{
alert(err.message);
}
}
function processRequest(e) {
try{
var prn=JSON.stringify(e);
alert("xhr.readyState-->"+xhr.readyState);
alert("xhr.status-->"+xhr.status);
alert("xhr response-->"+ xhr.response);
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.ip);
}
}
catch(err)
{
alert(err.message);
}
}
}
</script>

Why won't Javascript code run?

I'm new new to javascript. This is my first real attempt to do something besides running hello world. I'm attempting to retrieve information from a url and display it. I checked the url and it returns json. The "Hello World" code runs but as soon as I add the code that retrieves the json inside the script tags nothing happens. I'm getting no syntax errors.
<!DOCTYPE HTML>
<html>
<body>
<p>Header...</p>
<script>
document.write("Hello World");
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.send();
};
getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.query.count);
}
});
</script>
<p>...Footer</p>
</body>
</html>
I checked your html and js and one quick look into the console showed me that the problem was this line
alert("Your query count: " + data.query.count);
change the "data.query.count" to "data.length"
alert("Your query count: " + data.length);
Debuging code is one of the easiest ways to find errors.
You can hit F12 in basicly any browser to inspect the things behind the scene
If you examine the console on your browser you will see that your code is throwing the error of Uncaught TypeError: Cannot read property 'count' of undefined.
This is because you are attempting to access the length of the response array by means of data.query.count, when in fact it should be data.length.
So the working code should look like;
<!DOCTYPE HTML>
<html>
<body>
<p>Header...</p>
<script>
document.write("Hello World");
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.send();
};
getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.length);
}
});
</script>
<p>...Footer</p>
</body>
</html>

if-URL-exists check with 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...");

Categories

Resources