title: Setting Cookie with Ajax Request
body: <p>I have a php page with a form, that has a button. When the button is clicked, a jquery function is run, which performs some validation tests, then submits the form using ajax. In the php script run by ajax, a cookie is set. Immediatly after the cookie is set, I then try to get the cookie value, which I echo from the script and spit out in the success function of the ajax request. The cookie value hasn't set. </p>
  
  <p>Code is as follows. </p>
  
  <p><b>mainpage.php</b></p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $( document ).ready(function()
      {
          $('#submit_compare_stage1').click(function()
          {
              //Validation stuff
  
              if (passed_validation)
              {
                  var form_data = $('#compare_form').serialize(); //Collect query details into a form
  
                  $.ajax({
                      type: "POST",
                      url: "scripts/process_compare.php",
                      data: form_data,
  
                      success: function(data)
                      {
                          alert(data);
                      },
  
                      error: function(jqXHR, textStatus, errorThrown)
                      {
                          //Error stuff
                      }
                  });
              }
  
              return false;
          });
      });
  &lt;/script&gt;
  
  &lt;form name="compare_form" id="compare_form" action=""&gt;              
      ....
  
      &lt;button id='submit_compare_stage1' name='submit_compare_stage1'&gt;Next&lt;/button&gt;
  &lt;/form&gt; 
  </code></pre>
  
  <p><b>process_compare.php</b></p>
  
  <pre><code>&lt;?php
      //MySQL Stuff
  
      makeCookie('cs', '2');
  
      echo 'hi' . getCookie('cs', false);
  
      echo "success";
  
      function makeCookie($name, $contents, $length = 3600)
      {
          // Create a new cookie
          setcookie($name, $contents, time() + $length, '/');
      }
  
      function getCookie($name, $delete = true) 
      {
          // Return the contents of a cookie and delete it if requested
  
          $contents = $_COOKIE[$name];
  
          if($delete) {
              setcookie($name, '', time() - 3600, '/');
              setcookie($name, '', time() - 3600);
          }
  
          return $contents;
       }
  ?&gt;
  </code></pre>
  
  <p>The ajax request is posting alert messages saying "hisuccess" so the cookie isn't being set. </p>
  
  <p>I'm not sure if it's because the page needs refreshing or something else, but I do know the code used to work when we had a regular submit the form using action="/process_compare.php" and an iframe to put results into. </p>
  
  <p>Can anyone help? </p>