Dhruvi Mistry Dhruvi Mistry - 4 months ago 31
MySQL Question

Insert data into mysql database using ajax in php

I am trying to insert value using ajax in php, but data is not inserted in database. I have taken this code from the questions answered in other question from this site. Can anyone suggest where am I making mistake..?

<script>
$("#submit").click(function() {
var name= $("#name").val();
var password= $("#password").val();

$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});


});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<?php
//------insert.php------
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


$name=$_POST['name'];
$pass=$_POST['password'];
$sql= mysqli_query($conn,"INSERT INTO insert_tbl(name,pass) VALUES('".$name."','".$pass."')");

?>

Answer
<script>
  $("#FORM_ID").submit(function() {
                var name= $("#name").val();
                var password= $("#password").val();

                $.ajax({
                    type: "POST",
                    url: "insert.php",
                    data: "name=" + name+ "&password=" + password,
                    success: function(data) {
                       alert("sucess");
                    }
                });


            });
</script>

and also either load

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

before your script tag or use

 <script>
$(document).ready(function(){
      $("#FORM_ID").submit(function() {
                    var name= $("#name").val();
                    var password= $("#password").val();

                    $.ajax({
                        type: "POST",
                        url: "insert.php",
                        data: "name=" + name+ "&password=" + password,
                        success: function(data) {
                           alert("sucess");
                        }
                    });


                });
        });
    </script>
Comments