My application is making a network call using xmlHttpRequest. In the response i am getting Set-Cookie header (verified with fiddler). I need to access these cookies from javasript. I tried with XmlHttpRequest.getAllResponseHeaders(), it is returning all headers except Set-Cookie.
Is there a way to access these cookies from javascript? If yes, please provide some example.
My application is running on Webbrowser control (IE10), Windows Phone 8.
Thanks in advance.
While awaiting a more specific answer, you can instead send all the cookies set from the server through a post response, then set it locally, as so (using jQuery to make it easier):
// Client
var cookie;
$.post('example.com',{'stuff':'data'},function(data){
cookie = data;
});
// Server
if(isset($_POST['stuff'])) echo WhateverTheCookieWouldBe;
Actually cookies can be accessed via
document.cookie // this will return a string contains all cookie values separated by semicolon
This is actually not true since because of the async nature of request
// Client
var cookie;
$.post('example.com',{'stuff':'data'},function(data){
cookie = data;
});
alert(cookie); // undefined
Related
So I am trying to retrieve an rss feed in a synchronous call like so:
var oReq = new XMLHttpRequest();
oReq.open("GET", topicsUrl, false);
oReq.setRequestHeader("Access-Control-Allow-Origin", "*");
oReq.send();
The Send throws a Network Error, but did at one stage work. This is a cross domain xhr request that needs to be synchronous. I have tried to use the onreadystatechange between the header and the send but it didn't help. If I use an Asynchronous call the return data parsing starts before there is any data returned? So I'm a little puzzled how I can get this to work
The server needs to respond to your request with the Access-Control-Allow-Origin: * header. You sending it from the client does nothing.
I know this has been asked before in various forms, but I can't seem to get around the problem.
I have tried using both jQuery and the native JS API to make the Ajax requests.
My situation is the following (see attached diagram):
Browser makes HTTP request
Server responds and sets persistent Cookie
Browser makes HTTP Ajax request, Cookie is there alright
Server responds as expected, updates Cookie
Browser makes HTTPS Ajax request, Cookie is not there anymore (?!)
Server gives "default" response, since there is no Cookie (unintended behaviour)
Before anybody starts a lecture on cross-domain requests let me state a couple of things:
I know that this is a cross-domain request (different protocol), and that's why the Server sets the Access-Control-Allow-Origin header in the response (and I am using Chrome and Firefox, both of which support CORS)
What I also know, though, is that the HTTP cookie ought to be manageable over HTTPS (see here) since the host is the same
(EDIT) The cookie is properly set for the general domain (e.g. .domain.ext) and neither the HttpOnly nor the Secure flags are set
So, why, why, why doesn't the browser pass on the cookie when making the HTTPS Ajax call? Any ideas? I am about to lose my mind...
+-----------+ HTTP Request +-----------+
|Browser |+---------------->|Server |
+-----------+ +-----------+
HTTP Response
<----------------+
Set-cookie
Ajax HTTP Req.
+---------------->
Cookie (OK)
HTTP Response
<----------------+
Set-cookie (OK)
Ajax HTTPS Req.
+---------------->
No Cookie (!!!)
Ok, found the solution to the cookie problem.
See XHR specs, jQuery docs and StackOverflow.
The solution to have the cookies sent when switching protocol and/or subdomain is to set the withCredentials property to true.
E.g. (using jQuery)
$.ajax( {
/* Setup the call */
xhrFields: {
withCredentials: true
}
});
Document.cookie and Ajax Request does not share the cookie. Otherwise, ajax can't access the cookies from document.cookie or the response headers. They can only be controlled by the remote domain.
If you first get response including cookie from server by ajax, Since that you can request ajax communication with cookie to server.
For this case, you write such as below code (jQuery)
$.ajax({
xhrFields : {
withCredentials : true
}
});
See this article and demo
I have a page in domain.com that makes a JSONP ajax request (using jQuery's .getJSON() function) to a URL in anotherdomain.com. I thought (read: assumed) that the resource in anotherdomain.com would have server-side access to any cookies set in that domain, but that doesn't seem to be the case?
The ajax call is being done specifically to access a particular cookie, do some data manipulation and return a rich set of information keyed by the cookie value. The original domain doesn't have direct access to the cookie value, so I thought that an ajax request would maintain the state I need.
Which pivotal piece of information about cookies am I overlooking? I'm exhausted and I'm just not seeing it.
Thanks.
UPDATE
I found a way of doing it, but it looks like JSONP to my eye, so I'm wondering why this way works while the Ajax version doesn't. Is the request just disconnected from the browser session so that no cookies are accessible?
<script type="application/x-javascript" src="<?php echo $service_url . '&callback=interests' ?>"></script>
<script type="text/javascript">
function interests( data ) {
$( function() {
var c_behaviors = data.length;
var ids = [];
for( var i = 0; i < c_behaviors; i++ ) {
ids.push( data[i].behavior_id );
}
$('body').append( '<p><label>Returned:</label> ' + ids.join( ', ' ) + '</p>' );
});
}
</script>
The same origin policy applies to all ajax requests, so if the domain being accessed in an ajax call is different than the domain loaded in the browser (document.host), all cookies associated with the domain in the requested url will not be sent up. Therefore, the JSONP approach works because it writes out a new script tag in the window, which will behave like any resource request a browser could make to an external domain (hence passing all the cookies associated with the domain in the url). I have also confirmed this by simply calling $.post("http://atdmt.com") from my chrome console, while on stackoverflow.com in the browser (the only other domain that had cookies in my browser, while writing up the answer) and it did not send up any cookies in the request headers.
Another solution to get around the problem of maintaining state for anotherdomain.com would be to have anotherdomain.com set a first party cookie (by not setting the domain attribute of the cookie) and when an ajax/json request is made to anotherdomain.com access those cookies via javascript and push them up the request using standard HTTP params.
Hope I have helped.
I have encountered the same problem before. The issue I found is that most browsers won't let you ESTABLISH a session (i.e. set a session cookie) when the same origin policy isn't being met.
I'm working on a mobile web-app using sencha touch, HTML5 and phonegap as a wrapper.
I'm using PHP-Authentication (Cookie) and ajax-requests. Everything works fine on safari or chrome, but after the deployment with phonegap (webview) it does't work anymore...
Any help would be appreciated :)
Some more details:
All data for my app is loaded via ajax requests to my server component "mobile.php".
I use basic PHP-Auth to autenticate the user:
AJAX-Request [username, password] -> mobile.php
-> Session established (cookie)
All other requests if auth was successful
What's the difference between a normal safari website and the webview?
i figured it out:
you have to change the phonegap_delegate.m file and add the following to the init method:
- (id) init
{
/** If you need to do any extra app-specific initialization, you can do it here
* -jm
**/
//special setting to accept cookies via ajax-request
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage
sharedHTTPCookieStorage];
[cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
return [super init];
}
it enables webview to accept cookies from ajax requests
If your Phonegap AJAX requests are not firing callbacks like they're supposed to, this may be the reason.
If the response you're getting attempts to set cookies and you haven't done Michael's fix then your (jquery) AJAX request will fail quietly -- neither success: nor error: callbacks will fire despite the fact that the server actually received the request and sent a response. It appears you must do this even if you don't care about the cookies.
I hope this helps someone.
I didn't care about the cookies but just spent a few hours trying to figure out why the callbacks didn't fire!
There is a solution that works on android too:
Install plugin https://github.com/wymsee/cordova-HTTP to perform arbitrary HTTP(S) requests.
Replace XMLHttpRequest with the plugin alternative (cordovaHTTP.get or cordovaHTTP.post):
cordovaHTTP.post("https://example.com/login", {email: 'xyz#example.com', passwd: "s3cr3t"}, {}, function(response) {
console.log('success');
console.log(response);
}, function(response) {
console.log('failure');
console.log(response);
});
The response will contain status, data and response.headers["Set-Cookie"], that can be parsed for name, value, domain, path and even HttpOnly flags ;-)
Said cookie can be saved in LocalStorage and sent in subsequent requests (see cordovaHTTP.setHeader() or header parameter of .get/.post methods) to simulate an authenticated user on a desktop browser.
Best ways to store get and delete cookie its working fine in my app which is on live
To store value in cookie
window.localStorage.setItem("key", "value");
To Get value in cookie
var value = window.localStorage.getItem("key");
To Delete cookie value
window.localStorage.removeItem("key");
window.localStorage.clear();
I know when you request a page normally it is typically the case that you would use server side session data and set cookies via HTTP headers, but does it work the same when the content is requested via AJAX?
An AJAX request contains the same request/response information as a traditional HTTP request. You can set cookies on the client once the async callback is executed, etc.