I'm using Topaz Signature pads & implementing their new AJAX library. I want to display a warning on the page if the page if the driver/service is not installed/running. To do this, the script makes a get request to a domain which redirects to localhost via the hosts file.
If the service is running, I get the status of the signature pad & everything is fine. If however, the service is not installed or not running, I just get NS_ERROR_FAILURE and the script halts, even if I'm within try{code}catch(err){errorcode}
try {
console.log('connect: ' + TabletConnectQuery());
}
catch(err){console.log('Caught ' + err);}
My console just shows:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://tablet.sigwebtablet.com:47290/SigWeb/TabletState. (Reason: CORS request failed).
Line 0
NS_ERROR_FAILURE:
https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js line 2 > eval
Line 151
This is particularly troublesome as it occurs during a page transition & stops the animation dead.
I ended up getting it to work by modifying the SigWebTablet.js library topaz provided.
Changed
function SigWebGetProperty(prop) {
var xhr = SigWebcreateXHR();
if (xhr) {
xhr.open("GET", baseUri + prop, false );
xhr.send(null);
if (xhr.readyState == 4 && xhr.status == 200) {
return xhr.responseText;
}
}
return "";
}
To:
function SigWebGetProperty(prop) {
var xhr = SigWebcreateXHR();
if (xhr) {
xhr.open("GET", baseUri + prop, false );
try{
xhr.send(null);
}
catch(err){
return "";
}
if (xhr.readyState == 4 && xhr.status == 200) {
return xhr.responseText;
}
}
return "";
}
Related
I have an API that returns 302 status code with the destination location.
But when i am calling this API from my angular code, the browser is not redirecting to destination URL. Rather it's calling that destination URL(which is an HTML page) with XHR and giving error like:
error: SyntaxError: Unexpected token < in JSON at position 0 at Object.parse () at XMLHttpRequest.onLoad
text: "\n
Basically it tried parse the HTML response as JSON and failed.
So how can I make browser to redirect to destination URL rather than calling it as XHR.
Browser won't jump to the Location which is returned by XHR 302 response's header. If you want to let the browser redirect, you should make it by your own.
Here is the code:
const url = 'http://your-api.com'
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
// This means our request undergoes a redirection
if (xhr.responseURL !== url) {
window.location = xhr.responseURL
}
else {
// Do something else, like JSON.parse(xhr.responseText)
}
}
}
xhr.open('GET', url)
xhr.send()
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.
I'm creating a website to progress in javascript and I have a little problem, every ways I try, my browser doesn't want to load my json file.
I tried many codes i found on internet but none of them work (or I don't know how to make them work). Finally i fond this one which is quite easy to understand but yhis one too doesn't work and always return an error message.
function loadJSON(path,success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 1) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path , true);
xhr.send();
}
function test()
{
loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}
I run the test function but everytimes, the console return me an error. Someone have an idea to solve my problem ?
status is the HTTP response code.
200 means the request has been successful. The status will most likely never be 1.
Here is a list of HTTP codes
As a solution, I suggest using the fetch API, which is the modern way to query files.
Here are some examples on how to use it
If you really want to use AJAX, use this :
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Source : You Might Not Need jQuery
I have a domain A "xbo.dev" and a sub domain B "blog.xbo.dev".
For example, on B domain, I would like to make an Ajax request to a domain A function.
I'm trying this with FOSUserBundle authentication. What I do :
var xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open('POST', 'http://xbo.dev/ajax/check_login_ajax', true);
// I am using hard coding for the URL because with Routing.generate I would have this URL : http://blog.xbo.dev/ajax/check_login_ajax
// which is not good because the request is on a different domain
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr);
console.log('ok');
} else {
console.log('ko');
}
}
};
xhr.send(encodeURI('_username=' + $('#co_'+varName+'username').val() + '&_password=' + $('#co_'+varName+'password').val() + '&_remember_me=' + false + '&_csrf_token=' + $('#co__csrf_token').val()));
I have a "ok" displayed by my request but nothing special is happening (I should have something like "Bad credentials" or "success" (or others), returned by FOSUserBundle check_login_ajax function, but no one of those is displayed...)
How can I do ?
EDIT 1 : Here is the result I have each time, either the login / password are correct or not
And with a normal $.ajax, I have this :
You need to implement something to relax the same-origin policy such as CORS.
As to your in-code note about hard-coding vs using the router to generate URLs, Symfony's router supports hostnames.
I have the following headers set on the server
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
response.addHeader("Access-Control-Allow-Headers","X-Custom-Header");
And i want to use the POST method to access a web service and send data to it but the problem is my setting up with the server is causing problems
I used the following method
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Safari/Firefox.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
and based on this object
url = "http://myurl.do";
var xhr = createCORSRequest('POST', url);
if (!xhr) {
alert('CORS not supported');
return;
}
var params = "name=pari123&action=initaction&gameId=slotreel3";
xhr.setRequestHeader('Content-Type', 'application/text/plain');
if(xhr.readyState == 4 && xhr.status == 200)
{
alert('Tested OK')
xhr.send(params);
}
else
{
alert('status not 200 or xhr is not ready');
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
But always it alerts a message saying 'status not 200 or xhr is not ready' i am not able to proceed any one if you know please kindly help!
when i print the xhr.readyState its printing a value of 1
if(xhr.readyState == 4 && xhr.status == 200)
This check must be placed in the onreadystatechange event handler. You obviously cannot have a 200 status code or a "finished" request before actually sending it.
What you wanted is probably this:
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert('Tested OK');
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
}
};
xhr.send(params);
If you want an else case to check for errors remember that you still need to check for xhr.readyState == 4. You don't want your error-handling code to run for other readyStates.
There is no need for the onload event - when you get readyState == 4 you know the request has finished.
There can be several issues here.
I observed that different browsers implement CORS differently. My experience is based on Firefox and Google Chrome. For example, I had to add a special header on server side, so that Firefox would make the preflight (OPTIONS) request and the actual request (GET,PUT etc.) using one connection as Google Chrome does it. You would have to add on the server side:
response.addHeader("Keep-Alive", "timeout=2, max=100");
response.addHeader("Connection", "Keep-Alive");
I also noticed that some browsers do not like the wildcard ("*") in the CORS headers. A workaround for the line
response.addHeader("Access-Control-Allow-Origin", "*");
would be to return the origin of the request and not a wildcard.
However, there could be also other problems and we would need more details. For example, does the request work when the server is hosted on the same domain (i.e. the problem might not be related to CORS). What server are you using?
xhr.send(); needs to be just after the call to xhr.open(); does it not? Status 1 means the request has not been sent yet, it'll never get to status 4 unless you actually send the request..