Bengau
Bengau

Reputation: 175

radio buttons and cookie settings

I don't know anything about cookies or how to set them and I need some advice. I have two radio buttons. For example if an option is changed from one to another, that option will remain even if the page is refreshed or changed on other pages where this radio buttons exist, and I need to make the cookie setting for this code. Can someone can give me some advice regarding what code should I add to my php?

This is js code:

$(document).ready(function() {
  $('radio[name=radio]').each(function() {
   $(this).click(function() {
    my_function();
    });
   });
});

my_function()
{
   var value_checked = $("input[name='radio']:checked").val();
   $.ajax({
   type: 'POST',
   url: 'page.php',
   data: {'value_checked':value_checked},
   });
}

html code

<form>
    <div id="radio">
        <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Choice 1</label>
        <input type="radio" id="radio2" name="radio" /><label for="radio2">Choice 2</label>
    </div>
</form>

Upvotes: 0

Views: 1908

Answers (2)

L0j1k
L0j1k

Reputation: 12645

It is important to remember that cookies can only be set before any output is sent to the client on a webpage, because cookies are set as headers, and headers can only be sent prior to any part of the webpage output. Therefore, you need to refresh the page to set a cookie to the value of your radio button.

At the very top of the php, BEFORE the <!DOCTYPE> html or <html> tag, you need to add something like this:

<?php
if(isset($_POST['radio1'])) {
  setcookie('radio1', true, 600, '/');
  setcookie('radio2', false, 600, '/');
} else if(isset($_POST['radio2'])) {
  setcookie('radio2', true, 600, '/');
  setcookie('radio1', false, 600, '/');
}
?>

The above code will make sure that only one of the cookies is set to true and the other is set to false. The cookies will expire after ten minutes.

This is after you properly set up the html form so that you can detect that your user has selected a button:

<form method="POST" action="index.php">
  <div id="radio">
    <input type="radio" id="radio1" name="radio" checked="checked" />
    <label for="radio1">Choice 1</label>
    <input type="radio" id="radio2" name="radio" />
    <label for="radio2">Choice 2</label>
  </div>
</form>

The PHP Manual page has more information: http://php.net/manual/en/function.setcookie.php

EDIT: Semantic code changes and fixed the html tags described.

Upvotes: 1

Anton Bessonov
Anton Bessonov

Reputation: 9813

See setcookie examples how to set cookies in PHP. But you can do it also with javascript js_cookies.

Upvotes: 1

Related Questions