How to overcome the http request status zero in a local machine - javascript

There is a lot of same questions but i cannot find the answer so i am reposing the same question.I am receiving an json request using java script
var request = null;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return null;
}
request.open("GET", url, true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
}
} else
alert(request.status);
}
I am receiving an status code zero while i receive the request the javascript runs on apache server and json request will be received from tomcat server everything is local . can any one tell me how to over come it.
Note: i cannot use any framework.

I suspect that you are violating the same origin policy restriction that is built in browsers. This restriction prevents you from sending cross domain AJAX requests. So for example if the page containing the AJAX call is hosted on http://localhost/example.htm and you are trying to send an AJAX request to http://localhost:8080/somescript you won't be able to do so because the domains do not match (different ports).
The best way to ensure that your AJAX requests work is by only using relative urls:
request.open("GET", "/somescript", true);

Related

Fetch XML without getting blocked (CORB)

For example I want to fetch https://www.w3schools.com/xml/simple.xml
to my website http://example.com.
This is the code
var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://www.w3schools.com/xml/simple.xml', true);
xhr.onload = function () {
if (xhr.readyState === 4 && this.status === 200) {
console.log(this);
}
}
xhr.send();
I'm getting an empty response and a warning saying
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://www.w3schools.com/xml/simple.xml with MIME type text/xml. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Then I had been studying these CORB rules. Some developers are saying that it is not possible to get data from another origin.
But is it really the case?
In the project I'm working on, it is a public xml feed, and since the owner are updating the feed quite often - and I would like to have my website in sync with the feed - I assume it is not possible? Do I really have to create a xml file, and copy-paste the xml data and upload it to my server each time?
Or is there a way to fetch this data directly from the url somehow?
You could create a PHP script like this:
<?php
header("Content-type: text/xml");
echo file_get_contents('https://www.w3schools.com/xml/simple.xml');
?>
Call this simple.php and then amend your Javascript to call simple.php instead:
var xhr = new XMLHttpRequest();
xhr.open("GET", 'simple.php', true);
xhr.onload = function () {
if (xhr.readyState === 4 && this.status === 200) {
console.log(this);
}
}
xhr.send();

httpRequest.status code 0 when attempting to retrieve array from local JSON file using AJAX

I'm trying to retrieve an array from a JSON file named questions.json (that is in the same folder as the JavaScript file). To overcome the same origin policy, I've allowed XMLHttpRequest to access local files using the Chrome --allow-file-access-from-files switch.
I've looked up other questions related to this, but I'm still not sure why my request fails. Is the failure related to my AJAX call to localhost? Is what I am doing a valid HTTP request? Did I not overcome the same origin policy?
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
console.log(httpRequest.status);
if (httpRequest.status === 200) {
var allQuestions = httpRequest.responseText
} else {
console.log('There was a problem with the request.')
}
} else {
console.log('The request is still not ready.')
}
}
httpRequest.open('GET', 'questions.json', true);
httpRequest.send(null);
My console shows that the request is still not ready (3 times), that XHR has finished loading, that the httpRequest.status is 0, then that there was a problem with the request.

Is it secure to call a PHP file from JavaScript?

I have a simple HTML5 Canvas game and at the end of a part I want to store variables in MySQL. Is it secure to do this with XMLHttpRequest, Ajax or anything? This is how I started to write it:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var success = request.responseText;
alert(success);
}
}
request.open('GET', 'saveLevel.php?name='+name+'&level='+level, true);
request.send();
My problem with this is that everyone can do this in console like this:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var success = request.responseText;
alert(success);
}
}
request.open('GET', 'saveLevel.php?name='+name+'&level=100', true);
request.send();
(How) can I solve it?
You can use the combination of Authentication, Obfuscation and Minification to secure you JavaScript Network Calls
Sample JS Obfuscator Library JScrambler
Sample JS Minification Library UglifyJS
Authentication-
I assume,your API has some sort of authentication field (e.g. Hash/Token etc.). If not, you can integrate it with - This answer.
Make sure you use a salt, (or even API key) that is given to your JS client on a Session Basis. This way, you can prevent it from unauthorized access.
On the server side, remember the last few endpoint calls, and before allowing another one, check if your logic allows for the new one right now.
If you follow the steps above it will certainly make it very secure.

CORS not working at all

The SDK demo works fine (it doesn't need special CORS stuff since it is on the same domain)
When I try to send the request from localhost:8080 this happens
So I'm trying to request api.soundcloud.com/tracks - first my browser sends an OPTIONS req to api.soundcloud.com asking if it's okay to call cross-origin. api.soundcloud.com does not return the headers my browser is looking for so my browser throws an error and can't make the request.
Am I the only person trying to use the APIs from another domain or is something going wrong here?
EDIT: Doing debugging in wireshark - when making an API call using the SDK in the browser an OPTIONS request isn't even being sent. WTF
here's a working example where request is coming from jsbin.com:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
}
};
request.open('GET', 'http://api.soundcloud.com/tracks?client_id=YOUR_CLIENT_ID');
request.send();

Ajax - "Access-Control-Allow-Origin" Error

I'm trying to work with the Livestream API to see if a certain channel is live but keep getting this error:
XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin http://www.webdevstl.com is not allowed by Access-Control-Allow-Origin.
Do I need to run it through PHP or am I doing something wrong in my ajax call? It's pretty straight forward code:
function getActive(){
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
console.log(json);
}
}
xmlhttp.open("GET", "http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
getActive();
You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will fail - unless explicitly permitted by the remote host.
You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.
CORS would also be an option, but that assumes you having access to the remote server's config.

Categories

Resources