0

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."')");

 ?>
6
  • Do you see your success alert() message? Commented Aug 2, 2016 at 19:46
  • no..I can not..@showdev Commented Aug 2, 2016 at 19:47
  • 1
    It's possible that your form is submitting via its default action before the AJAX can fire. Try return false; at the end of your click handler to prevent the default action. Also, do you see any errors in your browser console or server logs? Commented Aug 2, 2016 at 19:48
  • html alert("sucess"); to alert(data); / insert.php: where a return? to success, add later $sql is echo "success"; Commented Aug 2, 2016 at 19:50
  • @showdev do mean adding return false in $("#submit").click(function() {}); or should I add another js.? ..nop there is no error..that's the main issue.. Commented Aug 2, 2016 at 19:51

5 Answers 5

3
<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>
Sign up to request clarification or add additional context in comments.

1 Comment

Just to clarify for the OP, note the event change from click to submit.
1

This is html form for insert data

<form id="frmrecord" method="post">
    <input type="text" name="txtusermame" />
    <input type="password" name="txtpassword" />
    <input type="submit" value="Insert" />
</form>

Use this code for call insert.php file to insert data

jQuery(document).ready(function ($) {

    $("#frmrecord").submit(function (event) {
                event.preventDefault();
                //validation for login form
        $("#progress").html('Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');

            var formData = new FormData($(this)[0]);
            $.ajax({
                url: 'insert.php',
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) 
                {
                    //show return answer
                    alert(returndata);
                },
                error: function(){
                alert("error in ajax form submission");
                                    }
        });
        return false;
    });
});

After calling file you can receive data in php file Insert.php

<?php 
  $usernmae=$_POST['txtusername']; 
  $password=$_POST['password']; 
  $sql= mysqli_query($conn,"INSERT INTO insert_tbl(name,pass) 
    VALUES('".$usernmae."','".$password."')");
 ?>

Download Demo

Comments

0

You can use this ajax to insert data in database.

 $(document).ready(function() {
        //register
        $("#register_btn").on("click", function() {
            $("#register_btn").html(
                'Please Wait ...'
            );
            $(".error").html("");
            $.ajax({
                type: "POST",
                url: "register-submit.php",
                dataType: "json",
                data: $("#register_form").serialize(),
                success: function(response) {
                    alert(response.mesage)
                    $("#register_btn").html("Sign Up");
                },
                error: function(error) {
                    console.log(error);
                    $("#register_btn").html("Sign Up");
                },
            });
        });
    })

At "register-submit.php" you will place your PHP code file name with path. you can check this tutorial for complete example.

Comments

0

Php DB connection(Postgres)

<?php
$db = pg_connect("host=localhost port=5432 dbname=demo user=postgres 
password=selva27");
?>

Php Insert

 <?php
// session_start();
// print_r($_POST);die;
require_once'db.php'; 

//error_reporting(0);

$name = $_POST['cname'];
$address = $_POST['address']; 
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone']; 

$sql="insert into 
demo(col1,col2,col3,col4)values('val1',val2,val3,val4)";

$result = pg_query($sql);

if($result){

echo 'Data stored sucessfully';
  }

else{
  echo'Data not stored';
}

pg_close($db);
exit();

?>

Php Fetch

<?php
require_once'db.php';
 
$date='set datestyle=SQL,DMY';
$select="select * from manpower order by manid";
pg_query($date);
$result=pg_query($select);
$data=array();
    
    while($row=pg_fetch_assoc($result)){
        $data[]=$row;
 
 }
 
 
echo json_encode($data);
exit();

  ?>

Php Delete

<?php
require('db.php');
if(isset($_GET['id']))
{
 $sql = "DELETE FROM manpower WHERE manid=".$_GET['id'];
 pg_query($sql);
 echo 'Deleted successfully.';
}

?>

Php Edit

<?php
require_once'db.php';
if(isset($_GET['id'])){
$id=$_GET['id'];
$select="select * from manpower where manid=$id";
$result=pg_query($select);
$data=array();
    
    while($row=pg_fetch_assoc($result)){
        $data[]=$row;
 
 }
 
 }  
 echo json_encode($data);
 exit();
 ?>

Php Update

<?php
require_once'db.php';
// print_r($_POST); die;
$id=$_POST['id'];
$name=$_POST['name'];
$dob=$_POST['dob'];
$skill=$_POST['skill'];
$address=$_POST['address'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];
$remarks=$_POST['remarks'];

$update="update manpower set name='$name',date_of_birth='$dob' skill_code=$skill
where manid=$id";
$result=pg_query($update);
if($result){
echo"Updated successfully";
}
else{
echo"Something wrong";
}
?>

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?
-1
     <script>
      var formData = new FormData($("#form")[0]);
      $.ajax({
    url: "emp_insert.php",
    type: "post",
    processData:false,
    contentType:false,
    data: formData,
    success: function (d) {
        // alert(d);

    swal(d, "", "success", { button: "ok" });

        $("#form")[0].reset();

    },

   });
    </script>

File upload php

     <?php
     session_start();
    // print_r($_POST);die;
    require_once 'db.php';
    //error_reporting(1);

    $emp_name = $_POST['emp_name'];
    $dob = $_POST['dob'];

    $aadhar = $_POST['aadhar'];
      $cid = $_POST['cid'];
      $woid = $_POST['woid'];
      $c_emp_id = $_POST['c_emp_id'];
      $wop_from = $_POST['wop_from'];
     $wop_to = $_POST['wop_to'];
     $doj=$_POST['doj'];
     $designation = $_POST['designation'];


        $filename = $_FILES["photo"]["name"];
    $target_directory = "upload/"; 
     $target_file = $target_directory.basename($_FILES["photo"]["name"]); 
  //name is to get the file name of uploaded file 
    $filetype = strtolower (pathinfo($target_file, PATHINFO_EXTENSION));
    $newfilename = time().".".$filetype;
    move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file); // 
    tmp_name is the file temprory stored in the server //Now to check if 
    uploaded or not 
// if(move_uploaded_file($_FILES["file"]["tmp_name"], $newfilename)) 

  $sql="select * from 
 employee('$emp_name','$dob','$filename',$aadhar,$cid,$woid,'$wop_from',
'$wop_to','$doj','$c_emp_id','$designation')";
 $result = pg_query($sql);
 //move_uploaded_file($tmp, $target);
 if($result){

   echo 'Data stored sucess';
   }

 else{
   echo'Data not storedd';
    }

  exit();

?>

1 Comment

WARNING: this is a very bad code, full of security breaches

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.