Q:

Alert function is not working in the js code

here is my Index file:
<!Doctype html>
<html>
<head><title>The Database Entry Project</title></head>
<body>
    <div>
        <form>
            <h3>Input Details Here</h3>
            <label for="fn">First Name</label>
            <input id="fn" type="text">
            <label for="ln">Last Name</label>
            <input id="ln" type="text">
            <br><br>
            <input type="submit" value="Register" id="sub">
            <input type="submit" value="Login" id="log">
            <input type="reset" value="Reset">
        </form>

    </div>
    <script type="text/javascript" src="js/sub.js"></script>
    <script type="text/javascript" src="js/jquery.js"></script>
</body>
</html>

this is sub.js
//-------------------------------Register----------------------------
$(function () {
    $('#sub').on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();

        var fn = $('#fn').val();
        var ln = $('#ln').val();
        $.ajax({
            url: 'php/login.php',
            type: 'post',
            data: {
                'fn': fn,
                'ln': ln
            },
            success: function (data) {
                alert(data);
            },
            cache: false
        }); // end ajax call
    });
});
//-------------------------Login---------------------------------------
$(document).ready(function(){
  $('#log').on("click",function(e){
    e.preventDefault();
    e.stopPropagation();

    var fn = $('#fn').val();
   var ln = $('#ln').val();

   $.ajax({
      url: 'php/log.php',
      type: 'post',
      data: { 'fn': fn , 'ln': ln },
      success: function(data) {
        alert(data);

      },
      cache: false
    }); // end ajax call

   });
});

this is sub.php
<?php
session_start();
require 'config.php';
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$stmt = $dbh->prepare("INSERT INTO tab1(fn,ln)VALUES(?,?)");
$stmt->execute(array($fn, $ln));
echo "Saved Successfully";
?>

this is log.php
<?php
session_start();
require 'config.php';

$fn = $_POST['fn'];
$ln = $_POST['ln'];
$stmt = $dbh->prepare("SELECT fn, ln FROM tab1 WHERE fn=? AND ln=?");
// $stmt->bindValue(1, $fn);
// $stmt->bindValue(2, $ln);
$stmt->execute(array($fn,$ln));
$row = $stmt->fetch();

if($row > 0) {
  echo "Login Successful";
}

else {
  echo "Login failed.";
}

?>

The config file for connecting to database is working properly.
PHP files are working right(when individually tested)
I don't understand why alert function is not working in sub.js file and also why data is not inserting in the database.

A:

Your JavaScript error console will be complaining that $ is undefined.
You are including sub.js (which depends on jQuery) before you include jquery.js. 
Swap the order of your script elements.

