This question already has answers here:
"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page
(13 answers)
Closed 3 years ago.
I am very new to coding, and have a problem with my site. I am getting an error message that says:
Mixed Content: The page at 'ajax-utils.js:34 Mixed Content: The page at 'https://daringtrifles.github.io/courserahtmlcssjavascript/module5realsol/index.html' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://davids-restaurant.herokuapp.com/categories.json'. This request has been blocked; the content must be served over HTTPS
Here is my AJAX code. Could you guys please tell me where my mistakes are and how I could solve them?
(function(global) {
// Set up a namespace for our utility
var ajaxUtils = {};
// Returns an HTTP request object
function getRequestObject() {
if (window.XMLHttpRequest) {
return (new XMLHttpRequest());
} else if (window.ActiveXObject) {
// For very old IE browsers (optional)
return (new ActiveXObject("Microsoft.XMLHTTP"));
} else {
global.alert("Ajax is not supported!");
return (null);
}
}
// Makes an Ajax GET request to 'requestUrl'
ajaxUtils.sendGetRequest =
function(requestUrl, responseHandler, isJsonResponse) {
var request = getRequestObject();
request.onreadystatechange =
function() {
handleResponse(request,
responseHandler,
isJsonResponse);
};
request.open("GET", requestUrl, true);
request.send(null); // for POST only
};
// Only calls user provided 'responseHandler'
// function if response is ready
// and not an error
function handleResponse(request,
responseHandler,
isJsonResponse) {
if ((request.readyState == 4) &&
(request.status == 200)) {
// Default to isJsonResponse = true
if (isJsonResponse == undefined) {
isJsonResponse = true;
}
if (isJsonResponse) {
responseHandler(JSON.parse(request.responseText));
} else {
responseHandler(request.responseText);
}
}
}
// Expose utility to the global object
global.$ajaxUtils = ajaxUtils;
})(window);
Your mistake is here:
request.open("GET", requestUrl, true);
requestUrl is http://davids-restaurant.herokuapp.com/categories.json i guess. You need to change that URL just a bit.
Change your Request URL from
http://davids-restaurant.herokuapp.com/categories.json
to
https://davids-restaurant.herokuapp.com/categories.json.
Just add an "s" to your http -> https
Now it should work.
Related
This question already has answers here:
"Cross origin requests are only supported for HTTP." error when loading a local file
(30 answers)
Closed 2 years ago.
[enter image description here][1]i was learning ajax . but when i tried fetching data from local file it showed me error due to cors.i tried installing allow-access control origin but it didnt work .please help me
this is my java script code
function loadData() {
// Create an XHR Object
const xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', '/data.txt', true);
// console.log('READYSTATE', xhr.readyState);
// Optional - Used for spinners/loaders
xhr.onprogress = function(){
console.log('READYSTATE', xhr.readyState);
}
xhr.onload = function(){
console.log('READYSTATE', xhr.readyState);
if(this.status === 200) {
// console.log(this.responseText);
document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
}
}
// xhr.onreadystatechange = function() {
// console.log('READYSTATE', xhr.readyState);
// if(this.status === 200 && this.readyState === 4){
// console.log(this.responseText);
// }
// }
xhr.onerror = function() {
console.log('Request error...');
}
xhr.send();
// readyState Values
// 0: request not initialized
// 1: server connection established
// 2: request received
// 3: processing request
// 4: request finished and response is ready
// HTTP Statuses
// 200: "OK"
// 403: "Forbidden"
// 404: "Not Found"
}```
[this the image of output which is showing error .][2]
[1]: https://i.stack.imgur.com/4YOqJ.png
[2]: https://i.stack.imgur.com/Bh1km.png
If you want to persist data in your client, use localStorage.
If you want to download data from a data source, use a web service.You can easily create a simple web server using Node and Express, for example (plenty of resources online), but this is beyond the scope of this answer.
In my website I am currently trying to write code to turn a link into a formatted attachment .
I am trying to write code to detect if the file exists
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
alert(doesFileExist("http://hexbugman213.net/favicon.png"));
However, I noticed a problem. When the website has a 404 handler like .htaccess, and I try to test it with the file, it sees that the website didn't return a 404, and therefore still says it exists.
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
alert(doesFileExist("http://hexbugman213.net/thisfiledoesntexist.mp3"));
Is there any way I can account for this and have it return "false" when the file doesn't exist even if there's a 404 handler?
You need to call the send() function on the XMLHttpRequest to make it actually make the request. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
Also, you may run into cross origin issues depending on exactly what URL you're trying to retrieve and where you're hosting the page from. Mozilla has some documentation on the subject if you're not familiar with it: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Here is an improved version of your JavaScript that checks for exceptions and calls the send() function.
function doesFileExist(urlToFile) {
try {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
alert(xhr.status)
if (xhr.status !== 200) {
return false;
} else {
return true;
}
} catch (e) {
alert(e);
return false;
}
}
alert(doesFileExist("https://server.test-cors.org/server?enable=true&status=200&credentials=false"));
alert(doesFileExist("https://server.test-cors.org/server?enable=true&status=404&credentials=false"));
alert(doesFileExist("https://www.google.com/"));
alert(doesFileExist("http://hexbugman213.net/thisfiledoesntexist.mp3"));
The host: https://www.test-cors.org/ in the example is useful for testing CORS.
im programming an app which uses XMLHttpRequest to connect with a server to receive data.
The Problem is that I only get in the readyState attribute the value 2. That means the connection with the server is established but no data is streaming yet.
The value I need is 3, that means the request is been processed, but never happens.
Anyone knows why this append?
Thanks.
var otro="hello Marcos";
var datosNTRIP="Hello World";
var url = "http://ntrip.itacyl.es:2101/ponf1"
function httpGet(theUrl)
{
var bucle = 0;
var xml = new XMLHttpRequest();
xml.open( "GET", theUrl, true); // false for synchronous request
xml.onreadystatechange=function(e)
{
datosNTRIP=xml.readyState;
if(xml.readyState === 3)
{
bucle+=1;
if(bucle<=lim && xml.status === 200)
{
// resultado.innerHTML="Sending data";
//alert(xml.responseText);
// break;
}
else if((bucle>lim)||(bucle>lim && xml.status!=200))
{
xml.abort();
}
}
postMessage(datosNTRIP);
};
xml.onerror = function(e)
{
// alert("error");
};
xml.send( null );
}
httpGet(url);
As the title says, I want to get the Response Header Date value, but I keep getting the following warning :
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
My code :
function getxmlhttp () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
return new XMLHttpRequest();
}else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
return null;
};
function srvTime(){
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.open('GET',"blank.php",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
console.log("raw " + xmlHttp.getResponseHeader("Date"));
return xmlHttp.getResponseHeader("Date");
};
When I switch this line:
xmlHttp.open('GET',"blank.php",true);
To be true, the value returns NULL.
So can this be done, or do I have to just live with the warning in the console?
Thank you
As your title states, you must make the request asynchronously. That means you have to issue the request and wait for it to complete to get the information. Something like this should work:
function srvTime(callback) {
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { // The operation is complete
console.log("raw " + xmlHttp.getResponseHeader("Date"));
callback(xmlHttp.getResponseHeader("Date"));
xmlHttp = null;
}
};
xmlHttp.open('GET', "blank.php", true);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
};
Note that you must change the signature of your srvTime method. You can't return the data from it, the caller must supply a callback function that receives the date once the request completes.
An example of how you would use this function with the new signature is as follows:
srvTime(function (serverDate) {
document.getElementById("clock").innerHTML = "Game Time: " + serverDate;
});
I am written the bookmarklet, which takes pictures and videos from a site and must send it to my server via AJAX. The problem is in crossdomain AJAX request - I have got an error:
XMLHttpRequest cannot load http://mysite.com/community/bookmarklet/. Origin http://www.some-nice-site.com is not allowed by Access-Control-Allow-Origin.
How to solve data sending to my server from third-part sites?
Note: I use only plane javascript, this is the stipulation of development.
my code:
function getXmlHttp(){
var xmlhttp;
if (typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
};
return xmlhttp;
};
function vote(data) {
var req = getXmlHttp();
req.onready = function() {
if (req.readyState == 4 & req.status == 200) {
alert('OK');
}
}
req.open('GET', 'http://mydomain.com/community/bookmarklet/');
req.send(JSON.stringify(data()));
};
function dataProcessing(){
//some processing
return data;
};
// I tried it, but not deeply understand.
function JSONPresponse(){
document.getElementById('popup_body').innerHTML = 'done!';
};
(function(){
function pasteIt(){
// this function is builds the form, which get data for dispatch to my server.
};
pasteIt();
document.getElementById('my_button').addEventListener('click', function() {vote(dataProcessing)}, false);
}());
It is quite clear... the site you are attempting is prohibiting connection from outside world. You can try by modifying your http headers in request. See:
Access-Control-Allow-Origin Multiple Origin Domains?
Cannot properly set the Accept HTTP header with jQuery
As #jakeclarkson told - JSON-P is the solution, not the only, but useful for me.
XMLHttpRequest is not needed anymore. Instead it vote(data) function creates the script to build URL with params:
function vote(data) {
var script = document.createElement('script'),
data = JSON.stringify(data());
script.type = 'text/javascript';
script.src = 'http://mysite.com/api/bookmarklet/?vids='+encodeURIComponent(data);
document.getElementsByTagName('head')[0].appendChild(script);
};
The script is fulfilled, so URL is called and params already in the server.