Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

ajax set cookie

  1. User

    ajax set cookie

  2. Assistant

    To set a cookie using AJAX (Asynchronous JavaScript and XML), you can use the document.cookie property in JavaScript.

    Here's an example of how you can do it:

    function setCookie(name, value, days) {
      var expires = "";
    
      if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        expires = "; expires=" + date.toUTCString();
      }
    
      document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    // Example usage
    setCookie("myCookieName", "myCookieValue", 7);
    

    In this example, the setCookie function takes three parameters: the name of the cookie, the value to be stored, and the number of days the cookie should remain active. It sets the cookie by assigning the desired value to document.cookie.

    Note that cookies are stored as strings and multiple cookies are separated by semicolons. Also, the path parameter in document.cookie is set to "/" to make the cookie accessible across the entire website.

    You can call this setCookie function within your AJAX request, passing the necessary parameters.