1

I am trying to read cookies set at the backend after an AJAX post, I've tried all remedies I can think of/came across but i don't know what I'm doing wrong.

This is a code snippet to get Headers from an AJAX request. I'm more interested in seeing the "Set-Cookie" header there but its not. What's wrong with this code?

<?php
if ($_POST){
    header('Content-Type: application/json');

    setcookie('test_'.rand(),'cors');

    echo json_encode(array(
        'name' => 'Cors',
        'server' => 'Local'
    ));
} else { ?>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    function post(){
        $.post(null,{
            xhrFields: {
                withCredentials: true
            }
        }).done(function(a,b,options){
            $('code').html(options.getAllResponseHeaders());
        });
    }

    $(function(){
        $('.post').click(post);     
    });
</script>
<a href="javascript:;" class="post">Send</a>
<hr></hr>
<strong>Response Headers</strong><br/>
<pre><code>---</code></pre>

<?php } ?>
sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
  • answer here: http://stackoverflow.com/questions/2870371/why-is-jquerys-ajax-method-not-sending-my-session-cookie – MrE Jun 21 '16 at 22:31

1 Answers1

0

The XmlHttpRequest spec for getAllResponseHeaders states:

Return all the HTTP headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2

Which basically means you can't do it, at least that way.

Maybe you can try reading the cookies from the document.

Community
  • 1
  • 1
kojo
  • 737
  • 6
  • 14
  • Thanks Kojo, that actually helped. I used document.cookie in place of options.getAllResponseHeaders() and it was able to read the cookies. – Geofrey Ssekirime Jul 08 '14 at 11:33