简体   繁体   中英

AJAX PHP, on button click pass variable from javascript prompt to php script to set cookie?

newbie here. i'm experimenting with ajax and php lately just for learning purposes, i have this simple html:

<button type="button" id="setc">Set Cookie</button>

on click i want to ask for a variablename and value so i could pass it on my php script, here's my js code:

$("#setc").click(function(){
    var cookieVar = prompt("Enter a cookie variable","");
    var cookieVal = prompt("Enter the variable's value","");
    $.ajax({
        url:'setcookie.php',
        type: 'POST',
        data: "cookieVar="+cookieVar+"&cookieVal="+cookieVal,
        success:function(data){
            console.log(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(textStatus+errorThrown);
         }
    });
});

and here's my php script:

<?php
    $cookieVar="";
    $cookieVal="";
    echo setcookie($cookieVar,$cookieVal);
?>

but when i clicked the button it gives me this error:

" : Cookie names must not be empty in on line " :第 cookie名称不能为空”

how can i make it work?

Four issues I can think of, all with PHP:

  1. Your PHP script tries to use $cookieVar and $cookieVal without declaring them. PHP has no idea what these are

  2. setcookie tries to set http headers. echo tries to output content to the browser. You cannot set headers after you've output content (unless you have some buffer settings allowing this). This is probably not a problem in this case (since the inner function runs first), but to be safe I would set the cookie first, then echo on a separate line.

  3. setcookie doesn't return the cookie value, so if you're trying to get that with echo setcookie(...) it won't work. That function returns true if the cookie is successfully set, and false otherwise.

  4. Only use the PHP closing tag ?> if you intend to send content to the browser -- some HTML -- after it. Using a closing tag otherwise increases the possibility of unwanted spaces and line returns (whatever comes after) to be sent to the browser.

Modify your PHP to:

<?php
//capture values sent by the browser
$cookieVar = $_POST['cookieVar'];
$cookieVal = $_POST['cookieVal'];

//set cookie and send result
if(setcookie($cookieVar,$cookieVal)===true){
    echo "Successfully set cookie $cookieVar to $cookieVal";
}
else{
    echo "Failed to set cookie $cookieVar to $cookieVal"
}

Notice, no closing ?> .

In your ajax, it's better to use:

 $.ajax({
    url:'setcookie.php',
    type: 'POST',
    data: {cookieVar: cookieVar,
           cookieVal:cookieVal
    },...

And your php setcookie.php. Do like BeetleJuice tell you..

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