Ajax request with JavaScript responds with 302 (Found) - javascript

I am trying to send data by Ajax with the Post method, but the answer gives me 302 (Found) and I do not know what it can be. This is my code:
function sendData(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log("Response" + xmlhttp.responseText);
}
}
xmlhttp.open("POST", "request.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+document.getElementById('username').value);
}
and my .php file only print a message
<?php echo 'hello : ' . $_POST["name"] ?>

The 302 status code indicates that the resource you are requesting has redirected to another resource. If this is behind some authentication, or requiring a session to be active then yes, it would follow that the session timing out is responsible for the ajax resource being called to redirect to possibly a login screen maybe.
Try to use jQuery request, as it much simpler - also recommended in the above comments!

One way to get such a message is, to forget to add a / to the end of a URL, which is a "sub-directory" of the document root. As the URL your.domain/whatever and your.domain/whatever/ might not be the same. (Depending on server configuration, and the actual application serving those URLs.)
I can see, in this case you are actually POSTing to /request.php, so this might not apply, but just in case, I'd try to make that request 'by hand' and see what happens.
There are many browser plugins, that let you generate AJAX queries.

Related

Native ajax call does not redirect on 302

I have been googling for hours now. I've read a dozen "answers" on Stackoverflow, all of them using jQuery.
This is the common answer...
The ajax-request will follow that redirect afaik
Well, it doesn't.
I am trying to send a PUT from a form via native JS AJAX
[Please I beg you, don't tell me to use jQuery. I found a bug in jQuery via PUT
(1) so I'm going around it]
This is my code snippet...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
This block works great, I can POST, PUT and DELETE without issues. The server receives the data and updates the DB according to the sent METHOD just fine.
My (SLIM based) PHP, upon successful completion, returns a 302 and a URL to go to.
This process works using POSTMAN hitting the PHP, and it goes to the right page.
Opening Chrome Tools/Network, it shows that the PHP is returning a 302 and than a 200
My response object contains the full HTML for a page in the responseText property.
Funny thing is, if I hard code a bad URL,the browser goes to my 404 page fine.
Your thoughts? (Please don't ask me or tell me to use jQuery)
EDIT/ADDENDUM -----------------------
I have discovered that the redirect is using the same METHOD of the original call.
I'm doing
PUT /user/1
the Redirect is doing
PUT http://myserver.test/
This is the right place to go. Now I understand the 405.
I don't have a PUT route defined, therefore the 405.
I create a PUT route and it works in POSTMAN but still gives me a 405 in Chrome and Firefox.
I have 2 issues to solve:
1) change the METHOD on the redirect
2) figure out why the browser doesn't like the 307
I found "a" solution. I'm not sure I like it, but...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
window.location.replace(xhr.responseURL); // <---- solution
}
};

Cross-subdomain request

I need to make a cross subdomain request. There is a classic asp site which create an XMLHttpRequest to my PL/SQL Oracle webpage.
The asp site has the domain: test/site.asp and the PL/SQL webpage has the domain test:7779/site... so the top level domain is the same
This is my XmlHttpRequest:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onload = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
createChart(divID, xmlHttp.responseText, counter);
} else {
console.error("error");
}
}
};
xmlHttp.open( "GET", theUrl);
xmlHttp.setRequestHeader( "pragma", "no-cache" );
xmlHttp.send( null );
No error occurs in IE11, but in Chrome:
XMLHttpRequest cannot load http://test:7779/site
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://test' is therefore not allowed access.
The response had HTTP status code 501.
Is there a solution to make a cross subdomain request? Maybe with an iframe in my asp site, to get the content?
UPDATE:
I know tried to set the document.domain at both sides to the same: test. But this also didn't solved the problem.
My suggestion is, why dont you use MSXML2.ServerXMLHTTP object, as you have Classic ASP in hand? So that XMLHttp request will be sent from server to server and not from browser.
You can use it like this,
Dim xmlhttp
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.setTimeouts 30,500,1000,1000
xmlhttp.Open "GET", "http://yourlink" & time, false
On Error Resume Next
xmlhttp.Send
If Err.Number Then
getBBstatus = "Could Not Retrieve Data"
Err.Clear
Else
getBBstatus = xmlhttp.ResponseText
' Do something with the response here
End If
On Error Goto 0
Set xmlhttp = nothing
Hope it helps, thanks.

xmlhttp request status 302

I am trying to write core java script application that can test and analyse the http request. I started with below code. Firebug net tab says 302 status error.
<script type="text/javascript">
$(document).ready(function(){
var req = new XMLHttpRequest();
req.open("GET","http://www.google.com",true);
req.onreadystatechange = statusListener;
req.send(null);
});
function statusListener(req){
if (req.readyState == 4)
{
if (req.status == 200) {
var docx=req.responseXML;
console.log(docx);
}
}
}
</script>
3xx status codes are redirections.
302 means "Found". Quote from w3.org:
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.
If you want to get the page it redirects to, you have to check the URI in the response headers with the getResponseHeader() method.
You can see here to see how to access the correct URI.

Access is denied. JavaScript error on request to secured page

On page SomePage.aspx, by JavaScript code (XMLHttpRequest) I call SecuredPage.aspx used next code:
var httpRequest = GetXmlHttp();
var url = "https://myhost.com/SecuredPage.aspx";
var params = "param1=" + document.getElementById('param1').value +
"&param2=" + document.getElementById('param2').value;
httpRequest.open("POST", url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
//Call a function when the state changes.
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
}
httpRequest.send(params); // HERE ACCESS IS DENIED.
//---------------------------------------------
function GetXmlHttp() {
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
// Code for Internet Explorer.
{
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
It throws an Access is denied error. If send to http (http://myhost.com/SecuredPage.aspx), it works fine.
How is it possible to resolve this problem?
If you wish to fetch an HTTPS page via Ajax you need to do it from an HTTPS page on the same domain, there is no other way, as long as you use Ajax. This is because of the same origin policy.
That said, there are plenty of ways to do this not using Ajax, for instance you can use frames.
Another way is to use JSONP, but this requires that you are fetching, well, JSON :)
A third way, that tends not to be very useful for production websites, but still can be fun to tinker around with, is to use YQL as a proxy.
Lastly you can always set up a serverside proxy of your own, so that you call an HTTP address that fetches the HTTPS page and sends it on, but this is rarely a good solution if it can be avoided.
This is because the browser considers http and https as 2 different sites/domains, and therefore you have to adhere to the same origin policy.
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
One way to solve it is using jsonp.
As it's been said, your problem is that your browser sees this as a cross domain request. Another way to accommodate this is to set up a crossdomain.xml file like this:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="myhost.com" />
<allow-access-from domain="ourhost.com" />
<site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>
I'm not an expert on this method, but I have used it successfully. Other domains can be added by adding more allow-access-from tags. You may need to do some fiddling. YMMV.

facebook graph api ajax XMLHttpRequest - Null result?

Summary: Keep getting null response despite public data and setting callback to enable cross domain JSON. Please help!
A similar question has been answered here
Using the new facebook graph api, ajax calls returns null (empty)
but I'm not using jquery and have tried to adapt my code to reflect that answer.
I'm trying to use a simple example to test a simple xmlhttprequest handler. I have this link in my page:
<a href='javascript:loadXMLDoc(\"https://graph.facebook.com/btaylor?callback=methodname\",\"\")'>AJAX LINK</a>
The callback=methodname parameter is to enable cross domain JSON
I'm using a generic XMLhttprequest builder:
var req; // Request object
function loadXMLDoc(url,params){
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
}
}
}
I then have a handler :
function processReqChange(){
if (req.readyState == 4) {
if (req.status == 200) {
alert("Done");
} else {
//alert("There was a problem retrieving the data:\n" + req.statusText);
alert("Status Code = "+req.status);
alert("There was a problem retrieving the data:\n");
alert("Failed : object = "+req);
alert(req.responseXML);
alert("Failed : response = "+req.responseText);
alert("Failed : status = "+req.statusText);
}
}else{
}
}
But I keep getting a null response (statusText OK, status code 0). Any ideas?
Thanks in advance
You can't make a cross-domain ajax request. Look into whether or not they support JSONP, or use the FB.api method from their javascript SDK
http://developers.facebook.com/docs/reference/javascript/FB.api
EDIT: I didn't read your post very thoroughly when I replied.
I see that you're adding the callback name to your ajax request, which isn't going to do any good because you're still making an XHR request, so it will still fail cross-domain. You seem to be misunderstanding how JSONP works.
Normally I'd just suggest using a framework like jQuery to abstract out the work that you shouldn't have to reinvent. If you're absolutely dedicated to doing this without jQuery, start by reading the wikipedia article on how JSONP works:
http://en.wikipedia.org/wiki/JSON#JSONP
The basic idea is:
Create a script node where the src attribute looks just like the URL you're trying to request now.
The server will respond with something like : methodname({"foo": "bar"}); instead of just JSON. Since this is being requested via a script node, your browser will execute the "methodname" function and pass in the results.
implement methodname(response) function to handle the response (i.e. do the work you intended to do in processReqChange)
Remove this line and try again:
req.setRequestHeader("Connection", "close");
It sets up the connection to close automatically, often before the send is complete.

Categories

Resources