1

I want to insert data in a database with Ajax but I am facing error:

Uncaught ReferenceError: insertData is not defined at HTMLInputElement.onclick (Modal.php:105)

Screen shot of error page.

Screen shot of error page

In Modal.php file contain my html and js.

My Modal.php file

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style>
  .modal-header, h4, .close {
      background-color: #5cb85c;
      color:white !important;
      text-align: center;
      font-size: 30px;
  }
  .modal-footer {
      background-color: #f9f9f9;
  }
  </style>

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
    $("#myModal").modal();

  function insertData(){
    //$("#signup").click(function(){
    var Fname = $("#Fname").val(); debugger;
    var Lname = $("#Lname").val();
    var age =   $("#age").val();
    var email = $("#email").val();
    var password =  $("#password").val();

  // AJAX code to send data to php file.
  $.ajax({
            type: "POST",
            url: "Insert.php",
            data: {Fname:Fname,Lname:Lname,age:age,email:email,password:password},
            dataType: "JSON",
            success: function(data) {

                alert(data.message);

            },
            error:function(err){
                console.log(err.responseText);
            }
        });
        //});
  }
    });
});

</script>

</head>
<body>

<div class="container">
  <h2>Modal Sign Up Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-default btn-lg" id="myBtn">Sign Up</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header" style="padding:35px 50px;">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4><span class="glyphicon glyphicon-lock"></span> Sign Up</h4>
        </div>
        <div class="modal-body" style="padding:40px 50px;">

          <form role="form" action="">
            <div class="form-group">
              <label for="Fname"><span class="glyphicon glyphicon-user"></span> First Name</label>
              <input type="text" class="form-control" id="Fname" placeholder="First Name">
            </div>

            <div class="form-group">
              <label for="Lname"><span class="glyphicon glyphicon-user"></span> Last Name</label>
              <input type="text" class="form-control" id="Lname" placeholder="Last Name">
            </div>

            <div class="form-group">
              <label for="age"><span class="glyphicon glyphicon-user"></span> Age</label>
              <input type="number" class="form-control" id="age" placeholder="Enter Age">
            </div>

            <div class="form-group">
              <label for="email"><span class="glyphicon glyphicon-eye-open">  </span> Email</label>
              <input type="email" class="form-control" id="email" placeholder="Enter Email">
            </div>



            <div class="form-group">
              <label for="psw"><span class="glyphicon glyphicon-eye-open"> </span>  Password</label>
              <input type="text" class="form-control" id="password" placeholder="Enter password">
            </div>
            <!--<div class="checkbox">
              <label><input type="checkbox" value="" checked>Remember me</label>
            </div>-->
              <input type="button" id="signup" onclick="insertData()" class="btn btn-success btn-block" value="Sign Up"/>
          </form>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
          <p><a href="#">Log In</a></p>
          <!--<p><a href="#">Password?</a></p>-->
        </div>
      </div>

    </div>
  </div> 
</div>
</body>
</html>

This is my Insert.php file. In Insert.php file I have coded all PHP code related to inserting data in a database.

<?php
include("connection.php");

//if(isset($_POST['submit']))
      //  {

    $Fname=$_POST["Fname"];
    $Lname=$_POST["Lname"];
    $Age=$_POST["age"];
    $EmailId=$_POST["email"];
    $Password=$_POST["password"];

$Insert = "INSERT INTO simpleform (First_Name, Last_Name, Age, Email_Id, Password) VALUES ('".$Fname."', ".$Lname."', '".$Age."', '".$EmailId."', '".$Password."')";
$Query=mysqli_query($con, $Insert);

//print_r($Insert);


if(!$Query) 
        {
            echo mysqli_error();
            $successArr = array('status'=>'false','message'=>'Data not inserted');
            $successJson = json_encode($successArr);
        }
    else
    {
        $successArr = array('status'=>'true','message'=>'Data inserted successfully');
        $successJson = json_encode($successArr);

        //echo "Successfully Inserted";

    }
    echo $successJson;
    //  }

    header('Location: http://localhost/javascript/Modal.php');
    ?>
Community
  • 1
  • 1
enesh pal
  • 39
  • 9
  • 2
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Aug 14 '18 at 12:47
  • 3
    **Never store plain text passwords!** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Aug 14 '18 at 12:47

2 Answers2

1

Put your insertData() javascript function out of the click event of id #myBtn as well as document.ready function. Cause its is inside the click event, code isn't able to find your function insertData();

Your script should be like this -

function insertData(){
    //$("#signup").click(function(){
    var Fname = $("#Fname").val(); debugger;
    var Lname = $("#Lname").val();
    var age =   $("#age").val();
    var email = $("#email").val();
    var password =  $("#password").val();

  // AJAX code to send data to php file.
  $.ajax({
            type: "POST",
            url: "Insert.php",
            data: {Fname:Fname,Lname:Lname,age:age,email:email,password:password},
            dataType: "JSON",
            success: function(data) {

                alert(data.message);

            },
            error:function(err){
                console.log(err.responseText);
            }
        });
        //});
  }
  
  
  $(document).ready(function(){
    $("#myBtn").click(function(){
    $("#myModal").modal();
    });
});
Mohammad Intsar
  • 443
  • 4
  • 6
  • Working fine Sir, Can you explain little more because I am new in jQuery. – enesh pal Aug 14 '18 at 13:48
  • Good . Yeah . Y not . Always keep your JavaScript function out of the document ready . All type of events like click , hover , change must be inside document ready . – Mohammad Intsar Aug 15 '18 at 20:04
0

You haven't closed this event call maybe that's why it is showing the error. Try closing it after the modal open command instead at the bottom after ajax call

$("#myBtn").click(function(){
    $("#myModal").modal();
}

I hope this will help

Exterminator
  • 1,221
  • 7
  • 14