title: Return http response code from PHP to AJAX
body: <p>I am trying to make a login page for a website. I have a function that uses AJAX to send a request to a PHP script to check if the proper username and password has been entered in. I send http_response_code(200) if the the query returns a successful result, otherwise I send http_response_code(403). However, the login function seems to not return any response status. The response seems to be undefined. In this case, the function gives me the window alert for the wrong password or username even if the correct password and username is entered.  What condition should I be checking to determine what the success function should do based on the http response code? Is there another way to return a condition to AJAX based on what the PHP script does?</p>
  
  <p>Here it the code for the login function.</p>
  
  <pre><code>function login(){
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  var dataString = 'username1=' + username + '&amp;password1=' + password;
  if (username == '' || login == ''){
      window.alert("Please fill in username or password.");
  }
  else{
      $.ajax({
          type: "POST",
          url: "login.php",
          data: dataString,
          cache: false,
          crossDomain : true,
          success: function(response) {
              if (response.status == 200) {
                  window.location = 'http://localhost/site.html';
              }
              else {
                  window.alert("The password or username you have entered is not valid");
              }
          }
      });
  }        
  return false;
  </code></pre>
  
  <p>}</p>
  
  <p>Here is my php script. </p>
  
  <pre><code>&lt;?php
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
  header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
  $password2 = $_POST['password1'];
  $username2 = $_POST['username1'];
  $connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");  
  $query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
  $row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
  if(!empty($row['username']) AND !empty($row['password'])) {
      session_start();
      $_SESSION['username'] = $username2;
      http_response_code(200);
      echo "Successful Login";
      exit;
  }
  else{
      http_response_code(403);
      echo "The password or username you have entered is not valid";
  }
  mysqli_close($connection);
  ?&gt;
  </code></pre>