Ajax request but no content - javascript

I'm trying to create an Ajax request and then parse the response header to get the "Location" attribute. This is my code :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 301) {
alert('test');
var header = request.getResponseHeader('Location');
console.log(header);
}
}
request.open('GET', hrefAttr, true);
request.send(null);
The problem is that for some reason, the request is send and the response is received too (red "GET" request+response in Firebug), but I don't get any "test" alert nor any text in the firebug console.
EDIT: This is the modified code :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if(request.readyState <= 3 && request.status == 301) {
alert('test');
var header = request.getResponseHeader('Location');
console.log(header);
}
else if (request.readyState == 0 && request.status == 301) {
alert('state0');
}
}
request.open('GET', hrefAttr, true);
request.send();
console.log(request.readyState) gives this sequence of states : 1, 1, 2, 4.
In the Firebug console tab the Http Request+Response show fine but in red (if that means anything).
Not sure why I it isn't working...
Edit : I'm using Firefox.
Thanks in advance !

Unfortunately, the XHR will follow the 301 and return the content of the redirected page. You can see the behavior documented at the W3C here.
If the XMLHttpRequest origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.
So basically, your request is following the 301 transparently. The browser is automatically redirected and you are unable to do what you intend to do. If you have control over the web server, this can be changed (albeit, against most advice).
Hope this helps!

Related

How to get detect a redirect with JS

I need to check if an external URL redirects and if it does, get the new URL.
I tried doing this:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status < 400 && this.status >= 300) {
alert('this redirects to ' + this.getResponseHeader("Location"));
} else {
alert('doesn\'t redirect ');
}
};
xhr.open('HEAD', 'http://example.com/test', true);
xhr.send();
from this post:
detecting a redirect with javascript - how?
but it gets blocked by CORS policy. Is there any way around that?

How to update URL from request response using javascript?

I have a JavaScript function that is attempting to closely emulate a form submit.
function fopen() {
var xhr = new XMLHttpRequest();
xhr.open("POST", open_url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
create: 0,
jobtype: jobtype,
name: document.getElementById("file-selector").value
}));
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.write(xhr.responseText);
}
else {
console.log('ErR0r')
}
}
}
The behavior is close to identical, but the URL is not being updated after the response. I see there is an xhr.responseURL attribute but how can I actually get this to show in the address bar? And is there an exact full JavaScript implementation of form submit I can refer to in order to keep things as similar as possible?
To change the page's URL, set window.location.href.

Stop Javascript execution while processing xmlhttprequest

I have a situation where if browser window is closed then i need to make an XmlHttpRequest and show the result in a pop before the window is closed. But in my current code the browser doesn't wait for XmlHttpRequest to complete as it is asynchronous and closes the window. how can i open a pop before the browser closes itself.
var xhr = new XMLHttpRequest();
window.onbeforeunload = sendRequest();
//method to send the request to server
function sendRequest(){
xhr.open('GET', "https://www.google.co.in/search?q=java", true);
xhr.send();
xhr.onreadystatechange = processRequest;
}
//method to process the output
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseText;
alert(xmlDoc);
}
}
the result(alert) should be visible before window is closed.
You can make change little bit in your JS codes:
Referred from documentation link: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Example
where we need to cancel the event as stated by the browser, events like refreshing/ reloading a page or going to back page.
function sendRequest(event){
event.preventDefault();
event.returnValue = '';
var __type= event.currentTarget.performance.navigation.type;
// __type === 1 || __type === 0 : comes when Browser refresh button is clicked...
// __type === 2 : Browser back button is clicked
if(__type === 1 || __type === 0 || __type ==2){
// write here your AJAX request code or you can create a function for AJAX request & call up that function
xhr.open('GET', "https://www.google.co.in/search?q=java", true);
xhr.send();
xhr.onreadystatechange = processRequest;
}
}
//method to process the output
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseText;
alert(xmlDoc);
}
// here you can write a code to close the browser window
}

JS: how to check if file exists in JS or AJAX?

i want to check if a local file exists, if it not exists i want to run an alert('File not exists!').
I tried something like this :
function isOnline() {
var xmlPath = "/test/test/myfile.xml"
var request=new XMLHttpRequest();
request.open("GET",xmlPath,false);
request.send();
if (request.readyState === 4){
return true;
}else{
alert('File Away!');
return false;
}
}
But this dont work.
i cant use PHP or jquery.
If you try to get a resource from a server means the file should be publicly accessible through an URL.
When you launch that request with the XMLHttpRequest object with request.send() that call is asynchronous so checking immediately the readyStateor status it will not assure you the end of the call.
function isOnline() {
var xmlPath = "/test/test/myfile.xml"
var request=new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("File was found on URL");
}else if (this.readyState == 4 && this.status == 404 ) {
alert("File away!");
}
};
request.open("GET",xmlPath,false);
request.send();
}
You should subscribe to the status change event and check the values of that change. So beyond checking for the readyState==4 to get the change to the end of the transaction you should check also for the status code. For example 200 means everything was ok or 404 means the resource was not found.
Check the specification for that codes here:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

how to get the source code based on url using java script?

i wrote some code to get the html source code but it is working only IE8,but not working on mozila and chrome , what is the problem , please give me suggestion.
my code
<script>
function processStateChange() {
statusDiv = document.getElementById("stats");
if (req.readyState == 0) { statusDiv.innerHTML = "UNINITIALIZED"; }
if (req.readyState == 1) { statusDiv.innerHTML = "LOADING"; }
if (req.readyState == 2) { statusDiv.innerHTML = "LOADED"; }
if (req.readyState == 3) { statusDiv.innerHTML = "INTERACTIVE"; }
if (req.readyState == 4) {
statusDiv.innerHTML = "COMPLETE";
statusDiv.innerHTML = req.responseText;
}
}
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} if (window.ActiveXObject) { // code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
} return null;
}
//req = new XMLHttpRequest("Msxml2.XMLHTTP");
req = GetXmlHttpObject();
debugger;
if (req) {
req.onreadystatechange = processStateChange;
req.open("GET", "http://whatismyipaddress.com/", true);
req.send();
}
</script>
i checked to debug the code IE was completely working the loop(req.readystate==4 to finally get the response text) but mozila or chromes are only working loop(req.readystate==2 after abort the loop), what is the problem, please give me some suggestion, using jquery or java script to solve the problem
Thank u
hemanth
Due to the same origin policy restriction you cannot send cross domain AJAX calls. The reason this works in IE is probably that you are using some old dinosaurish version of IE that has some bugs and allows such an AJAX request. But no modern browser will ever allow you to do that.
You can send AJAX requests only to the domain from which originated the page containing the javascript code sending the AJAX request.
There are some workarounds depending on the level of control you have over the remote domain. In your case I guess that you have no control over http://whatismyipaddress.com/. So your only option is to write a server side script on your domain that will serve as a bridge between your domain and the remote domain and then send the AJAX request to your script:
req.open("GET", "/myscript", true);

Categories

Resources