Search code examples
phpmysqlajaxinsert-into

Ajax insert data script not working correctly. How can i improve this code?


I created a page that have a Bootstrap Modal button. When user click on this button, a modal window open and display a form to insert data on Mysql table through Ajax and PHP code. What happens is that my Ajax Script not working properly. I tried to find similar questions but i didn't find a resolution:

  1. My Ajax php code not working correctly
  2. Why is code in AJAX success call is not working?
  3. How to insert into mysql table using ajax?

My table has 3 columns:

ID   --> INT(11) AI
name --> VARCHAR(100)
email--> VARCHAR(100)

And below is the Modal code that i'm using to add data through Ajax script:

<button type="button" class="btn btn-block btn-primary" data-toggle="modal" data-target="#dataModal>ADD USER</button>

<!-- Modal -->
<div class="modal fade" id="dataModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" >Add Users</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
         </div>
         <div class="modal-body">
            <form id="usersForm" method="post">
               <input type="text" name="name"/>
               <input type="email" name="email"/>
         </div>
         <div class="modal-footer">
         <button type="button" class="btn btn-secondary" data-dismiss="modal">CLOSE</button>
         <button type="submit" class="btn btn-success" id="submit" >ADD USER</button>
             </form>    
         </div>
      </div>
   </div>
</div>

To send data to database through PHP script (insert.php), i'm using this Ajax script code on my project:

<!--AJAX-->   

<script type="text/javascript">
$(document).on('submit','#usersForm',function(e) {
var Name = $("#name").val();
var Email = $("#email").val();

// AJAX code to send data to php file.
    $.ajax({
        type: "POST",
        url: "insert.php",
        data: {Name:name, Email:email},
        dataType: "JSON",
        success: function(data) {
         alert("Data Inserted Successfully.");
        },
        error: function(err) {
        alert(err);
        }
    });

 }

</script>

Below is the insert.php code that i'm using to insert data on Mysql table:

<?php

include('db_connect.php');

$Name = $_POST['name'];
$Email = $_POST['email'];

$stmt = $connection->prepare("INSERT INTO users (name, email) VALUES(:name, :email)");

 $stmt->bindparam(':name', $Name);
 $stmt->bindparam(':email', $Email);
 if($stmt->execute())
 {
  $res="Data Inserted Successfully:";
  echo json_encode($res);
  }
  else {
  $error="Not Inserted,Some Probelm occur.";
  echo json_encode($error);
  }

  ?>

And my PHP database connection script db_connect.php:

<?php

$username = 'root';
$password = '';
$connection = new PDO( 'mysql:host=localhost;dbname=system', $username, $password );

?>

If i put an action on form tag like this:

form id="usersForm" method="post" action="insert.php"

the data is sent to database but if i remove the action="insert.php" nothing happens when user click on submit button. I think is something related with my Ajax script. What could it be?


Solution

  • Here is the correction of your code. Try it. it works.

    Ensure that you include your jquery library.

    secondly, you did not set the id for email and name in the form input as per

    id="name" id="email"

    Thirdly, You should remove the form element around the text input. just remove this.

    <form id="usersForm" method="post">
    </form
    

    and use it like this below

         <input type="text" name="name" id="name"/>
           <input type="email" name="email" id="email"/>
     <button type="submit" class="btn btn-success" id="submit" >ADD USER</button>
    

    finally, in Ajax call, you set variable Email and Name as capital letter but in your php you are posting it as small letter. please be careful

    Below is the code as being amended

            <script src="jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $('#submit').click(function(){
    var Name = $("#name").val();
    var Email = $("#email").val();
    
    alert(Name);
    alert(Email);
    
    // AJAX code to send data to php file.
        $.ajax({
            type: "POST",
            url: "insert.php",
            data: {Name:name, Email:email},
            dataType: "html",
            success: function(data) {
             alert("Data Inserted Successfully.");
            },
            error: function(err) {
            alert(err);
            }
        });
    })
    });
    
    
    
    
    </script>
    

    or you can also use my newly tested code.

            <script src="jquery.min.js"></script>
    
    <script type="text/javascript">
    
    $(document).ready(function(){
    
    
        $('#submit').click(function(){
    alert('ok');
    
    var name = $('#name').val();
    var email = $('#email').val();
    
    //set variables to check for valid email
        atpos = email.indexOf("@");
        dotpos = email.lastIndexOf(".");
    
    
            if(name==""){
    
                alert('please Enter name');
    
    
            }
    
     else if(email==""){
    
                alert('please Enter Email');
    
    
            }
    
    
    else  if (atpos < 1 || ( dotpos - atpos < 2 ))
        {
            alert("Please enter correct email Address")
            return false;
        }
    
    
    
    
    
    else{
    
    $('#loader').fadeIn(400).html('<span>Please Wait, Your Data is being Submitted</span>');
    
    
    
    
    
    var datasend = "nm="+ name + "&em=" + email;
    
            $.ajax({
    
                type:'POST',
                url:'insert.php',
                data:datasend,
                            crossDomain: true,
                cache:false,
                success:function(msg){
    
    
    alert('message successfully inserted');
    
                    //empty name and email box after submission
    $('#name').val('');
                    $('#email').val('');
                    $('#loader').hide();
                    $('#alertbox').fadeIn('slow').prepend(msg);
                    $('#alerts').delay(5000).fadeOut('slow');
    
                }
    
            });
    
            }
    
        })
    
    });
    
    
    </script>
    
    
    
    
    
    
    <div id="loader"></div>
     <div id="alertbox"></div>
    
    
                   <input type="text" name="name" id="name"/>
                   <input type="email" name="email" id="email"/>
             <button type="submit" class="btn btn-success" id="submit" >ADD USER</button>
    

    Updated Section

    Try this. it will display a successful message after an ajax submission is ok

        <script type="text/javascript">
    
        $(document).ready(function(){
    
    
            $('#submit').click(function(){
    
    
        var name = $('#name').val();
        var email = $('#email').val();
    
        //set variables to check for valid email
            atpos = email.indexOf("@");
            dotpos = email.lastIndexOf(".");
    
    
                if(name==""){
    
                    alert('please Enter name');
    
    
                }
    
         else if(email==""){
    
                    alert('please Enter Email');
    
    
                }
    
    
        else  if (atpos < 1 || ( dotpos - atpos < 2 ))
            {
                alert("Please enter correct email Address")
                return false;
            }
    
    
    
    
    
        else{
    
        $('#loader').fadeIn(400).html('<span>Please Wait, Your Data is being Submitted</span>');
    
    
    
    
    
        var datasend = "Name="+ name + "&Email=" + email;
    
                $.ajax({
    
                    type:'POST',
                    url:'insert.php',
                    data:datasend,
                                crossDomain: true,
                    cache:false,
                    success:function(msg){
    
        if(msg=='success'){
        alert('message successfully inserted');
        }else{
    alert('message submission failed');
    }
                        //empty name and email box after submission
        $('#name').val('');
                        $('#email').val('');
                        $('#loader').hide();
                        $('#alertbox').fadeIn('slow').prepend(msg);
                        $('#alerts').delay(5000).fadeOut('slow');
    
                    }
    
                });
    
                }
    
            })
    
        });
    
    
        </script>
    

    php testing file eg. insert.php

    <?php
    
    
    $Name = $_POST['Name'];
    $Email = $_POST['Email'];
    
    
    echo "success";
    ?>
    

    so Your php file should look like

    <?php
    
    //include('db_connect.php');
    
    $Name = $_POST['Name'];
    $Email = $_POST['Email'];
    
    
    $stmt = $connection->prepare("INSERT INTO users (name, email) VALUES(:name, :email)");
    
     $stmt->bindparam(':name', $Name);
     $stmt->bindparam(':email', $Email);
     if($stmt->execute())
     {
      //$res="Data Inserted Successfully:";
      //echo json_encode($res);
    
    echo "success";
      }
      else {
     // $error="Not Inserted,Some Probelm occur.";
      //echo json_encode($error);
    echo "failed";
      }
    
      ?>