Setting Session/Cookie via ajax request made on other website
That's my problem: I have an website, example.com, in which index.html file a introduced a <script src="website.net/js.js"></script>
You can see, that this is on other web server.
In the js.js
I have some data that I want to send to php. For that, I am using Ajax. So, I made a request to "website.net/data.php"
using method get. In data.php
file everything is ok,I received the value, but I want to set a cookie which value is what I received through ajax. Here is the problem. The setcookie function says that the cookie was set, but when I check in the browser, there's no cookie!
It works fine if the index.html file where I use <script src="website.net/js.js"></script>
is hosted on the same domain where I am making the request. If it is on another domain, it doesn't work anymore.
I have read something about Ajax cross site, but I don't want to send something back to example.com. All I want is to send some data from example.com to 开发者_StackOverflow社区website.net and then setting a cookie based on that value.
From the example.net I take a single value. On website.net I receive that value, I check if it's not already a cookie set, if it's not, I set it. On the same page, website.net, I use this cookie too.
Where do you check if the cookie is set? On the domain example.com
or on the domain website.net
?
In case you try to access the cookie using example.com, it is simply not possible to write/access or do anything with a cookie of an other domain. This is for security reasons. If you could, every other website could access you cookie and steal your identity easily.
Try to set the cookie within an iframe. I'm not sure if you can actually set cookies for website.net using JavaScript just because js.js is loaded from that domain.
Thank you very much!
I found an other way to send the data to a php file without ajax using basic javascript and <img />
tag
For example: example.com has in index:
<script type="text/javscript" src="http://website.net/js.js"></script>
In the js.js file I have
var important_data = 123; //
var src = "http://website.net/process.php?important_data=" + important_data;
document.write('<img src="' + src + '"/> ');
Now, every time I load example.com, it sends to website.net the important data. I tried to set a cookie in process.php
file and it worked! I tested that idea on localhost (both 'websites' were in my local server), but it should works also between 2 different domains. I'll try to see if it works between 2 different websites. After that, I'll come back to share the result.
Thank you!
Later Edit: I checked if I can set a cookie using that method, and it works! It works great! The cookie for website.net is not setted for that domain, it is setted for example.com. Exactly how I want!
精彩评论