changing the referrer of an Ajax POST - javascript

Anyone knows if with jquery or general javascript, I can change the referrer from the header in an http ajax call?
basically I want it to be sent from my page but have a referrer from another page. Any information would be great.

The browser will overwrite the referrer always for the tests that I've done. Meaning you can't change the referrer of an ajax call.

You can use .setRequestHeader( 'referer', 'foo' ), but I'm not sure if the browser would just replace that with the proper one or not.
via jQuery, the .ajax() method allows headers as well (.get() and .post() don't)
Note that there's very little point to doing this as you can't do cross-domain AJAX and even attempting to do this could possibly trigger XHR security rules in some browsers and just stop the request altogether.

You can always use this :
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("header key", "header value")}
})
But ofcourse, the browser can have a different opinion about the referer header.
This should be tested :)

You can't do that with jQuery, but you CAN do that with fetch
Not sure if it would work for cross domain requests (you will obviously need at least CORS permissions for that) but it definitely does work for same domain + different page like in this example
fetch("http://example.com",{"referrer":"http://example.com/inbox","body":"{\"format\":\"root\"}","method":"POST"});

Related

How can I get HTTP response header using JS?

I tried so many tutorials online but everything I try is really old and fails - I can't even create an XMLHTTPRequest object!
I just want to get the header from google.com - how can I do that?
You would use xhr.getResponseHeader() to get a single header, or xhr.getAllResponseHeaders() to read all of the headers from an XMLHttpRequest response.
The reasons this won't work for you:
XMLHttpRequest is case sensitive. If you are using HTTP in all caps, it will fail.
Unless you are a google employee adding code to google.com, your request falls victim to the same origin policy. You'll have to use your server as a proxy to get headers from a google request.
You cant simply do this by JS. You'll have to use AJAX and do a server request to PHP,ASP, Java or whatever. The XMLHTTPRequest should do it - if you really want to do it manually. But it will really not work with foreign domains, so you are forced to do the XMLHTTTPRequest to a page on your server which will deliver the header.

Sending POST message with AJAX Problem

I am currently trying to send a POST message which works fine except for the error that there are not correct credentials. However, after I add the credentials header, the message type is changed into OPTIONS and fails. I do not understand how adding a header causes the type to change to OPTIONS. Any help would be appreciated.
ajaxRequest = $j.ajax({
url: url,
type: 'POST',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth),
}
success: function(data, status) {
console.log("Success!!");
console.log(data);
console.log(status);
},
error: function(xhr, desc, err) {
console.log(xhr);
alert('fail')
console.log("Desc: " + desc + "\nErr:" + err);
}
});
EDIT: just to be more clear, I can literally go in and comment out the setRequestHeader function and it sends the message POST.
The problem you're encountering is because of cross-domain restrictions when using AJAX. When you try to set an authorization header, the browser issues what's known as a pre-flight request to see if the server will accept requests from this domain.
A pre-flight request is typically sent as an OPTIONS request. If the server you're invoking doesn't return an Access-Control-Allow-Origin header that matches your domain, the AJAX request is blocked.
There's more on this here: Cross-Origin Resource Sharing
"User agents can discover via a preflight request whether a cross-origin resource is prepared to accept requests, using a non-simple method, from a given origin."
I've run into the same problem- there are a few possible workarounds depending on your scenario.
If you have any way of setting the above mentioned header on the 3rd party server (some applications/services offer this) then that's probably the easiest way.
There's also a javascript library called EasyXDM that may work for you, but again, it will only be of use if you have access to the 3rd party server to upload a configuration file for this library.
Other options to investigate are PostMessage and Cross Domain Iframe communication. The latter is more of an old-school hack, the former is the recommended approach for newer browsers. It won't work for IE6/7.
The option we will probably end up using is a simple proxy- invoke our own server with the AJAX request, and on the server invoke the 3rd party server. This avoids the cross domain issue entirely, and has other advantages for our scenario.
I guess this is a problem in Internet Explorer. without explicitly telling the request-method (POST|GET) the request header doesn't contain the custom-header in IE, but it works in other browsers.
Yet try to post this in the bugs for jquery. Also try in other browsers.
Edit 1 : I saw this as a bug in jQuery 1.4.x .... I reported a bug report now.
The OPTIONS response happens when the server does not know how to respond to the ajax request.
I've seen it happen often when trying to post to a third-party domain (i.e. cross-site posting)
The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
Have you tried:
Having some sort of callback on the url that is being posted to?
Explicitly setting the headers (I'm assuming you're using PHP) on the url that is being posted to?

jQuery ajax is making connection, but the response is blank?

i'm trying to make a test with ajax response using an external array as a config file...
But it isn't working, i'm getting always a blank response...
Can anyone point me the reason?
Here is the link of jsBin test: http://jsbin.com/udanu/2/edit
It looks like you have bumped into the Same Origin Policy. You cannot make Ajax requests to hosts outside your domain, unless you use JSONP, or some other technique to get around the policy.
You may want to check out the following Stack Overflow post for a few popular solutions to work around the SOP (mainly the JSONP, CORS and Reverse Proxy methods):
Ways to circumvent the same-origin policy
As you are trying to get data from another domain, maybe you should try using "jsonp" instead of "text" as a dataType.
EDIT: didn't see the previous answer.

JQuery ajax cross domain call and permission issue

I have this polling script to check if a text file is created on the server. Works great locally, but fails when the file is on a different domain. How would i rewrite this for cross domain support?
$.ajax({
url: 'http://blah.mydomain.com/test.txt',
type: "GET",
success: function(result) {
//Success!
window.location.replace(Successful.aspx');
},
error: function(request, status, error) {
setTimeout("VerifyStatus(" + pollingInterval + ")");
}
});
EDIT:
I ended up using YQL to solve the cross domain issue and although it works, YQL is really slow that's adding quite a bit of performance overhead. Can anyone suggest a better solution for cross domain JQuery calls?
Set the dataType to "JSONP" on your $.ajax() call. You'll have to make sure the response is properly formatted for it to work. Wikipedia has a good section on JSONP.
Ajax doesn't go cross domain. Your best bet is to create a php page on the local domain that does the check, and go to -that- with your ajax call.
To get cross-domain AJAX via jQuery, you might want to check this out:
http://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/
Almost modern browsers are now supporting cross domain with CORS protocol, so you can use Ajax jQuery to do your job without editing anything in your script code. The change is into your server, you need to enable your server with CORS. It's just the job with adding header fields in each responses to client to support CORS protocol. See an implementation example here.
http://zhentao-li.blogspot.com/2013/06/example-for-enabling-cors-support-in.html

A question about cross-domain (subdomain) ajax request

Let's say I have the main page loaded from http://www.example.com/index.html. On that page there is js code that makes an ajax request to http://n1.example.com//echo?message=hello. When the response is received a div on the main page is updated with the response body.
Will that work on all popular browsers?
Edit:
The obvious solution is to put a proxy in front of www.example.com and n1.example.com and set it so that every request going to a subresource of http://www.example.com/n1 gets proxied to http://n1.example.com/.
Cross domain is entirely a different subject. But cross sub-domain is relatively easy. All you need to do is to set the document.domain to be same in both the parent page and the iframe page.
document.domain = "yourdomain.com"
More info here
Note: this technique will only let you interact with iframes from parents of your domain. It does not alter the Origin sent by XMLHttpRequest.
All modern browsers support CORS and henceforth we should leverage this addition.
It works on simple handshaking technique were the 2 domains communicating trust each other by way of HTTP headers sent/received. This was long awaited as same origin policy was necessary to avoid XSS and other malicious attempts.
To initiate a cross-origin request, a browser sends the request with an Origin HTTP header. The value of this header is the site that served the page. For example, suppose a page on http://www.example-social-network.com attempts to access a user's data in online-personal-calendar.com. If the user's browser implements CORS, the following request header would be sent:
Origin: http://www.example-social-network.com
If online-personal-calendar.com allows the request, it sends an Access-Control-Allow-Origin header in its response. The value of the header indicates what origin sites are allowed. For example, a response to the previous request would contain the following:
Access-Control-Allow-Origin: http://www.example-social-network.com
If the server does not allow the cross-origin request, the browser will deliver an error to example-social-network.com page instead of the online-personal-calendar.com response.
To allow access to all pages, a server can send the following response header:
Access-Control-Allow-Origin: *
However, this might not be appropriate for situations in which security is a concern.
Very well explained here in below wiki page.
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Another solution that may or may not work for you is to dynamically insert/remove script tags in your DOM that point to the target domain. This will work if the target returns json and supports a callback.
Function to handle the result:
<script type="text/javascript">
function foo(result) {
alert( result );
}
</script>
Instead of doing an AJAX request you would dynamically insert something like this:
<script type="text/javascript" src="http://n1.example.com/echo?callback=foo"></script>
Another workaround, is to direct the ajax request to a php (for example) page on your domain, and in that page make a cURL request to the subdomain.
The simplest solution I found was to create a php on your subdomain and include your original function file within it using a full path.
Example:
www.domain.com/ajax/this_is_where_the_php_is_called.php
Subdomain:
sub.domain.com
Create:
sub.domain.com/I_need_the_function.php
Inside I_need_the_function.php just use an include:
include_once("/server/path/public_html/ajax/this_is_where_the_php_is_called.php");
Now call sub.domain.com/I_need_the_function.php from your javascript.
var sub="";
switch(window.location.hostname)
{
case "www.domain.com":
sub = "/ajax/this_is_where_the_php_is_called.php";
break;
case "domain.com":
sub = "";
break;
default: ///your subdomain (or add more "case" 's)
sub = "/I_need_the_function.php";
}
xmlHttp.open("GET",sub,true);
The example is as simple as I can make it. You may want to use better formatted paths.
I hope this helps some one. Nothing messy here - and you are calling the original file, so any edits will apply to all functions.
New idea: if you want cross subdomain (www.domain.com and sub.domain.com) and you are working on apache. things can get a lot easier. if a subdomain actually is a subdirectory in public_html (sub.domain.com = www.domain.com/sub/. so if you have ajax.domain.com/?request=subject...you can do something like this: www.domain.com/ajax/?request=subject
works like a charm for me, and no stupid hacks, proxies or difficult things to do for just a few Ajax requests!
I wrote a solution for cross sub domain and its been working for my applications. I used iframe and setting document.domain="domain.com" on both sides. You can find my solution at :
https://github.com/emphaticsunshine/Cross-sub-domain-solution

Categories

Resources