最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Setting Cookie with Ajax Request - Stack Overflow

programmeradmin1浏览0评论

I have a php page with a form, that has a button. When the button is clicked, a jquery function is run, which performs some validation tests, then submits the form using ajax. In the php script run by ajax, a cookie is set. Immediatly after the cookie is set, I then try to get the cookie value, which I echo from the script and spit out in the success function of the ajax request. The cookie value hasn't set.

Code is as follows.

mainpage.php

<script type="text/javascript">
    $( document ).ready(function()
    {
        $('#submit_pare_stage1').click(function()
        {
            //Validation stuff

            if (passed_validation)
            {
                var form_data = $('#pare_form').serialize(); //Collect query details into a form

                $.ajax({
                    type: "POST",
                    url: "scripts/process_pare.php",
                    data: form_data,

                    success: function(data)
                    {
                        alert(data);
                    },

                    error: function(jqXHR, textStatus, errorThrown)
                    {
                        //Error stuff
                    }
                });
            }

            return false;
        });
    });
</script>

<form name="pare_form" id="pare_form" action="">              
    ....

    <button id='submit_pare_stage1' name='submit_pare_stage1'>Next</button>
</form> 

process_pare.php

<?php
    //MySQL Stuff

    makeCookie('cs', '2');

    echo 'hi' . getCookie('cs', false);

    echo "success";

    function makeCookie($name, $contents, $length = 3600)
    {
        // Create a new cookie
        setcookie($name, $contents, time() + $length, '/');
    }

    function getCookie($name, $delete = true) 
    {
        // Return the contents of a cookie and delete it if requested

        $contents = $_COOKIE[$name];

        if($delete) {
            setcookie($name, '', time() - 3600, '/');
            setcookie($name, '', time() - 3600);
        }

        return $contents;
     }
?>

The ajax request is posting alert messages saying "hisuccess" so the cookie isn't being set.

I'm not sure if it's because the page needs refreshing or something else, but I do know the code used to work when we had a regular submit the form using action="/process_pare.php" and an iframe to put results into.

Can anyone help?

I have a php page with a form, that has a button. When the button is clicked, a jquery function is run, which performs some validation tests, then submits the form using ajax. In the php script run by ajax, a cookie is set. Immediatly after the cookie is set, I then try to get the cookie value, which I echo from the script and spit out in the success function of the ajax request. The cookie value hasn't set.

Code is as follows.

mainpage.php

<script type="text/javascript">
    $( document ).ready(function()
    {
        $('#submit_pare_stage1').click(function()
        {
            //Validation stuff

            if (passed_validation)
            {
                var form_data = $('#pare_form').serialize(); //Collect query details into a form

                $.ajax({
                    type: "POST",
                    url: "scripts/process_pare.php",
                    data: form_data,

                    success: function(data)
                    {
                        alert(data);
                    },

                    error: function(jqXHR, textStatus, errorThrown)
                    {
                        //Error stuff
                    }
                });
            }

            return false;
        });
    });
</script>

<form name="pare_form" id="pare_form" action="">              
    ....

    <button id='submit_pare_stage1' name='submit_pare_stage1'>Next</button>
</form> 

process_pare.php

<?php
    //MySQL Stuff

    makeCookie('cs', '2');

    echo 'hi' . getCookie('cs', false);

    echo "success";

    function makeCookie($name, $contents, $length = 3600)
    {
        // Create a new cookie
        setcookie($name, $contents, time() + $length, '/');
    }

    function getCookie($name, $delete = true) 
    {
        // Return the contents of a cookie and delete it if requested

        $contents = $_COOKIE[$name];

        if($delete) {
            setcookie($name, '', time() - 3600, '/');
            setcookie($name, '', time() - 3600);
        }

        return $contents;
     }
?>

The ajax request is posting alert messages saying "hisuccess" so the cookie isn't being set.

I'm not sure if it's because the page needs refreshing or something else, but I do know the code used to work when we had a regular submit the form using action="/process_pare.php" and an iframe to put results into.

Can anyone help?

Share Improve this question asked Jan 18, 2014 at 23:04 Pippa Rose SmithPippa Rose Smith 1,4165 gold badges19 silver badges42 bronze badges 4
  • Did u try by simply running the script (server side) if any cookie is generated ? – Abhik Chakraborty Commented Jan 18, 2014 at 23:16
  • sorry, i don't understand. It is definitely running the script because it is printing the echo 'success' bit. – Pippa Rose Smith Commented Jan 18, 2014 at 23:19
  • I meant your process_pare.php directly without ajax and try echo the cookie if its there. The path you have set correctly as / which should be accessible across the domain. – Abhik Chakraborty Commented Jan 18, 2014 at 23:21
  • Why are you still using cookies? – Mottie Commented Jan 19, 2014 at 0:24
Add a ment  | 

1 Answer 1

Reset to default 5

A cookie is sent as a header of the response. In the data argument, you get the body of the response, not the headers.

It seems, that the headers of the response, you get from getResponseHeader() or MDN - getAllResponseHeaders(), do not include the Set-Cookie headers.

But the cookies are handled transparently by the browser. So, in order to access the cookies, you can use the document.cookie property

$.ajax({
    ...
    success: function(data, status, jqxhr) {
        var cookies = [];
        if (document.cookie)
            cookies = document.cookie.split('; ');

        // do something with the cookies
    },
});

or use the jQuery Cookie plugin available at github.

发布评论

评论列表(0)

  1. 暂无评论