title: Login using jquery, ajax and php
body: <p>I'm doing a project for the school and I'm having some troubles with this login, I know how to do it in a different way, but I would like to learn how to do it this way.</p>
  
  <p>I don't really know why its not working (some parts probably don't have any logic and is why its not working), it always says the error message "Invalid credentials" from the alert.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
          $(document).ready(function() {
              $('#loginform').submit(function(e) {
                  e.preventDefault();
                  $.ajax({
                      type: "POST",
                      url: 'loginFinal.php',
                      data: $(this).serialize(),
                      success: function(data) {
                          if (data === 'CORRECTO') {
                              window.location = 'index.php';
                          }
                          else {
                              alert('Invalid credentials');
                          }
                      }
                  });
              });
          });
      &lt;/script&gt;
  
  &lt;/head&gt;
  &lt;body&gt;
      &lt;form id="loginform" method="post"&gt;
          Username: &lt;input type="text" name="username" id="username" value=""&gt;
  
          Password: &lt;input type="password" name="password" id="password" value=""&gt;
  
          &lt;input type="submit" name="loginsub" id="loginsub" value="Login"&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>And here is the PHP:</p>
  
  <pre><code>function Login() {
          $success = false;           
          try {
              $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
              $sql = "SELECT * FROM users WHERE username = ".$_POST['username']." AND password = ".$_POST['password']." LIMIT 1";
  
              $stmt = $con-&gt;prepare( $sql );
  
              $stmt-&gt;execute();
  
              $valid = $stmt-&gt;fetchColumn();
  
              if( $valid ) {
                  $success = true;
  
                  session_start();
                  session_regenerate_id();
                  $_SESSION['user'] = $_POST['username'];
                  session_write_close();
                  echo ('CORRECTO');
  
                  exit();
              }
  
              $con = null;
              return $success;
          }
          catch (PDOException $e) {
              echo $e-&gt;getMessage();
              return $success;
          }
      }
  </code></pre>