0

I am writing the below code to set the cookie only when the form with id=AuditDetails is submitted, however the following code sets the cookie every time the page reloaded. What am I missing?

$(document).ready(function() { //Initial call to the functions.
    showdept();
    $("#AuditDetails").on("submit", function() {
        document.cookie = "active_audit=1;path=/;expires=1;"
    });
});
Maulik
  • 97
  • 9
  • what is AuditDetails? paste your html please – user786 May 27 '15 at 06:28
  • @MohamedBelal `the form with id=AuditDetails is submitted`, it is form and don't need `click` event – Tushar May 27 '15 at 06:29
  • Can you check put alert on this submit section ? if alert comes 2 times means your code call 2 times. if your code 2 times come then you need to take some action. I don't think that this comes 2 times. – Sunny May 27 '15 at 06:32
  • Alex, it is a form as I mentioned in the question. – Maulik May 27 '15 at 06:32
  • Maybe you think it set when the page reload because your cookie is already saved did you delete your old cookie first ? – Mohamed Belal May 27 '15 at 06:33
  • I want to use the cookie value when the page is reloaded, and want to set the cookie only when the form is submitted. So there is no need to delete the cookie. And the code here should replace the cookie value. – Maulik May 27 '15 at 06:36

2 Answers2

0

You may need to reset the form once it is submitted

onsubmit="this.submit(); this.reset(); return false;"

So that only when it is re submitted, the cookies will be set.

rahulmishra
  • 620
  • 1
  • 13
  • 29
-1

Updated

There is solution on How to detect/track postback in javascript?

And

How can I check for IsPostBack in JavaScript?

You need on server side

  if(IsPostBack)
    {   
      ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var     isPostBack = true;", true);
    }

And on Client side

       if(isPostBack)  
                {   // do your thing

                }
        else
            {
                 $.cookie("name","value");
            }

$.cookie is jquery syntax. You can download jquery from http://code.jquery.com/jquery-1.11.3.min.js

And jquery plugin for cookie from here https://github.com/carhartl/jquery-cookie

add both script in script src="..."> in header of html

Basically you are writing javascript variable through server side script and reading it on client side

Hope this will help

Community
  • 1
  • 1
user786
  • 3,902
  • 4
  • 40
  • 72
  • ClientScript.RegisterClientScriptBlock is asp.net. if you are using java or php, then I am sure there must be equivalent of this present – user786 May 27 '15 at 06:35
  • I am new to javascript and all of this is unknown to me. I just do not understand why it is setting the cookie everytime I reload the page, while it should set the cookie only when the form is submitted. Could you help me with the code here? – Maulik May 27 '15 at 06:42