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.";
}

?>

I don’t understand why alert function is not working in sub.js file and also why
data is not inserting in the database.

Hi, Try to remove the single quote

 data: { 'fn': fn , 'ln': ln },

to this

 data: { fn: fn , ln: ln },

also I think you can remove this code

e.stopPropagation();

use the e.preventDefault();

Reverse the order of the script links, placing the jQuery library above the code that references it:

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

The library is meant to come first. Usually your browser console will point this out.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.