简体   繁体   中英

Jquery cookie-how to use cookie

I need to post ID value from page with jeasyui Grid, to another demo.php,for creating pdf report. So my idea was to use cookies, like this.

  $(function () {

        $("#btnCookie").bind("click", function () {
        var row = $('#tt').datagrid('getSelected');
    if (row){
            $.cookie("name",row.id);
          alert($.cookie("id"));//just to check for value ,and it is OK!
            window.location.href = "demo.php";
        }});
    });

after submit,I get right value. On demo.php I use this to get cookies value:

         $(function () {
        if ($.cookie("id") != null ) {
           var id = $.cookie("name");

            $.removeCookie("id");
           }
    });
</script>

now my problem is to put cookie values in next query in php section:

$result = mysqli_query($con,"SELECT * FROM stan where id="HERE I need cookie value"

What you're looking for is:

$_COOKIE["something"] 

I hope you find out the rest :) (Make sure you use proper quotes in your string, not like you wrote it in the question; also be aware of the syntax of implanting array element refs into strings; finally, watch out for cookie value, it can be manipulated so protect your query against tricky values.)

You're setting jQuery cookie correctly. To call it and search your database just use it in the query like so:

<?  
    $value = $_POST['rowValue'];

    $stmt = $con->prepare("
        SELECT * 
        FROM stan 
        WHERE id = ?
    ");

    $stmt->execute(array($value));

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);   
?>

EDIT: Updated because of comment:

<script>
$.post("demo.php", {
        rowValue: row.id //The cookie value
    }
});
</script>

So I now understand that you want to pass the cookie value, not the cookie name to your php file. For this you don't need to set a cookie, you can just send the value to the php file. In my example I've used the jQuery ajax post function. I've updated my example PHP accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM