0

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?

Michel Xavier
  • 133
  • 3
  • 14
  • 2
    Because your js is full of issues like not having `e.preventDefault()`, selecting non existing elements and passing the wrong fields to the server – Alon Eitan Feb 24 '19 at 21:31
  • I don't believe that you are getting the expected values? Add an alert to show what you get for the `Name` and `Email` values in the javascript. Where you retrieve the value for those is using the `#` (by id) jQuery selector, but the two inputs only have name and type attributes. – Paul T. Feb 24 '19 at 21:36
  • Thanks for the feedback. Actually my table has only 3 columns: ID, name and email. I put these fields in Ajax script _data: {Name:name, Email:email}_ to pass input values to insert.php file. In this case how can i improve this ajax script to pass input values to php insert data? – Michel Xavier Feb 24 '19 at 21:40
  • 2
    @paul it will work with a normal form submission because the input names are correct and the js doesn't prevent the submit action - that's why it work as long as the OP keeps the action attribute of the form element – Alon Eitan Feb 24 '19 at 21:43
  • 1
    @AlonEitan: Yes, that is correct for the normal submission, I was speaking more to the ajax part, which I should have clarified. – Paul T. Feb 25 '19 at 00:05

3 Answers3

1

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

  ?>
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
  • thanks for your feedback. Your Ajax script is working but before ajax send data to database, two alerts are displayed instead of Ajax success alert. In this case is it possible to display alert only after ajax success? – Michel Xavier Feb 25 '19 at 10:55
  • 1
    Just remove all those alert. its just for testing purposes that ajax is getting those values from the form input. just remove them.... – Nancy Moore Feb 25 '19 at 11:10
  • See my updated section of the answer. You can now get a succesful message after Ajax has successfully submitted your content...I have set the responses also on your php code. I will appreciate also an upvote from you on my answer. Thanks – Nancy Moore Feb 25 '19 at 11:41
1
<input type="text" name="name"/>
<input type="email" name="email"/>

In your form add ID attr to inputs.

<input type="text" name="name" id="name" />
<input type="email" name="email" id="email" />

Or try change your ajax:

var Name = $("#name").val();
var Email = $("#email").val();

to

var Name = $("#usersForm input[name="name"]").val();
var Email = $("#usersForm input[name="email"]").val();

Also add e.preventDefault(); for not refreshing page, after

$(document).on('submit','#usersForm',function(e) {
e.preventDefault();
ucoder92
  • 161
  • 1
  • 11
0

I found another way to solve this too:

<script>

$(document).on('submit', '#usersForm', function(event){
        event.preventDefault();
    $.ajax({
                url:"insert.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data){
                    alert('OK');
                    $('#usersForm')[0].reset();
                    $('#dataModal').modal('hide');
                }
});
});

</script>
Michel Xavier
  • 133
  • 3
  • 14
  • 1
    Michael Xavier you are wrong. which response are you getting from the php code to ensure that it was successful or not. see my updated code. You need to check if data() has a correct response from the php code something like if(data=='success'){ alert('message successfully inserted'); }. Am using success as its response from my php code. pl ease see my answer as being updated – Nancy Moore Feb 25 '19 at 11:46