9

I don't know how to delete a cookie. I want is when I submit a form. The cookie is also delete. I try the delete_cookie("name") but is not working. I think because the cookie I created by javascript. Please check my code to fix this problem.

This is my sample text field:

<input name="cargo_no" type="text"  class="validate[required]"  id="cargonumber" onchange="setCookie('cargonumberC', this.value, 365);"/>

and this is the javascript

function setCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();

    if (!nDays) 
        nDays=1;

    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
  }

document.addEventListener('DOMContentLoaded', function() {
  var themeSelect = document.getElementById('cargonumber');
  var selectedTheme = readCookie('cargonumberC');

  if (selectedTheme) {
    themeSelect.value = selectedTheme;
  }
});
Arturs
  • 1,258
  • 5
  • 21
  • 28
wewe
  • 193
  • 1
  • 5
  • 17
  • You can't delete a cookie. You must set the expiry to a date in the past (i.e. call the setCookie function with the exact same parameters for domain, path,name... and use '1970-01-01' for example as the date) AND when the page is refresh (reload or click to a link) the browser will delete the cookie – JScoobyCed Sep 02 '13 at 03:36
  • Expire a cookie, or set it to a not meaningful value. –  Sep 02 '13 at 03:37
  • Possible duplicate [javascript - delete cookie¨](http://stackoverflow.com/questions/2144386/javascript-delete-cookie) – Fabien TheSolution Sep 02 '13 at 03:37

4 Answers4

15

Using Codeigniter, put it inside the save method of your controller:

Try:

delete_cookie('name', $domain, $path); 

Details on official documentation

Usman Ahmed
  • 2,392
  • 1
  • 20
  • 17
Nivlem Castro
  • 188
  • 1
  • 10
10

You can delete cookie from CodeIgniter. Use cookie helper like

$this->load->helper('cookie');
delete_cookie("name");
Sarwar Hasan
  • 1,561
  • 2
  • 17
  • 25
0

To delete a cookie use:

helper('cookie');
delete_cookie('remember_me');
4b0
  • 21,981
  • 30
  • 95
  • 142
hanafa
  • 3
  • 3
-3

You can't delete a cookie. The browser (or the user) has the delete the cookie(s). But, you can make the browser auto-remove the cookie by setting the expiration of the cookie to a date in the past. Here's a JavaScript example.

function deleteCookie(cookieName, cookieValue) {

document.cookie = cookieName+"="+escape(cookieValue) + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";

}