SamFisher83
SamFisher83

Reputation: 3995

Ajax and cookies

I am not too much of a web developer so this might be a newbie question.

I am trying to do xml request where I send a user name and password. On the reply my server application will stick a cookie in the response header. Will this cookie be accessible using the document.cookie variable?

Upvotes: 0

Views: 152

Answers (2)

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6114

Yep, you definitely can. I made a program to test it.

HTML file:

<!DOCTYPE html>
<html>
<head>
<style>
div {
    position:relative;
    left:10px;
    top:10px;
    width:100px;
    height:70px;
    background-color:#F00;
}
</style>
</head>
<body>
<div onclick="sendRequest('cookieset.php')">Click me</div>
</body>
<script>
function sendRequest(address) {
    var xmlRequest = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
    if(xmlRequest == null) {
        console.log("Error: XMLHttpRequest failed to initiate.");
    }

    xmlRequest.onreadystatechange = function() {
        if (xmlRequest.readyState == 4) {   //Completed loading
            if (xmlRequest.status == 200 || xmlRequest.status == 0) {
                alert(document.cookie)
            }
            else    //Otherwise, there was a problem while loading
                xmlContainer.innerHTML = "Error " + xmlRequest.status + " has occurred.";
        }
    }
    try {
        xmlRequest.open("GET", address, true);
        xmlRequest.send(null);

    } catch(e) {
        console.log("Error retrieving data file. Some browsers only accept cross-domain request with HTTP.");
    }

}
</script>

</html>

PHP file:

<?php 
    setcookie("cookieTest", "good", 0); 
?>

Upvotes: 1

JW.
JW.

Reputation: 51638

Yes, as long as the cookie doesn't have the HttpOnly flag set.

Upvotes: 3

Related Questions