如何使用jQuery Ajax传递表单数据以在数据库中插入数据?

时间:2018-11-22 09:54:39

标签: php jquery ajax bootstrap-modal

我有4个表,即stud,country_master_academic,master_state和master_city。 主要问题是我的表单包含许多不同的字段,例如文本框,单选按钮,下拉列表和图像文件,因此我感到非常困惑。 我无法在数据库中插入数据。请帮我。我尝试了很多次,但是没有用。我在这里先向您的帮助表示感谢。 home.php页面中的模态

 <div class="container">
<div class="modal fade" id="add_data_modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-heading" style="margin-top:30px;text-align:center">
                <button class="close" data-dismiss="modal" style="margin-right:20px;font-weight:bold;">x</button>
                <h4 class="modal-title"><span class="glyphicon glyphicon-user"></span> Add Student</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                <form class="form-horizontal" name="form" id="form" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
                    <label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
                    <input type="text" class="form-control" name="name" id="name" pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters" required />
                </div>
                <div class="form-group">
                    <label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label><label id="p2">*</label>
                    <input type="text" class="form-control" name="mob_no" id="mob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits" required />
                </div>
                <div class="form-group">    
                    <label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label><label id="p3">*</label>
                    <input type="date" class="form-control" name="dob" required />
                </div>
                <div class="form-group">
                    <label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label><label id="p4">*</label>
                    <textarea rows="4" cols="33" class="form-control" name="add" id="add" required></textarea>
                </div>
                <div class="form-group">
                    <label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label><label id="p5">*</label>
                    <input type="file" name="photo" id="photo" required />
                </div>
                <div class="form-group">
                    <label for="gen"><b> Gender: </b></label><label id="p6">*</label><br/>
                    <input type="radio" name="gender" id="gender" value="M" required="required">Male
                    <input type="radio" name="gender" id="gender" value="F" required="required">Female
                </div>
                <div class="form-group">
                    <label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label><label id="p7"> *</label>
                        <?php
                            $country="SELECT * from country_master_academic";
                            $res= $conn->query($country);
                            if($res->num_rows>0)
                            {
                                echo '<select name="country" id="country" class="form-control" required>';
                                echo '<option value="">Select</option>';
                                while($row=$res->fetch_assoc())
                                {
                                echo '<option value='.$row["country_code"].'>'.$row['country_name'].'</option>';
                                }
                                echo '</select>';
                            } else {
                            echo "0 result";
                        }
                        ?>

                </div>
                <div class="form-group">
                    <label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label><label id="p8">*</label>
                    <?php
                        $state = "SELECT * from master_state";
                        $res=$conn->query($state);
                        if($res->num_rows>0)
                        {
                            echo '<select name="state" id="state" class="form-control" required>';
                            echo '<option value="">Select</option>';
                            while($row=$res->fetch_assoc())
                            {
                                echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
                            }
                            echo '</select>';
                        } else {
                            echo "0 result";
                        }
                    ?>
                    </div>
                <div class="form-group">
                    <label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label><label id="p9">*</label>
                    <?php
                        $city="SELECT * from master_city";
                        $res=$conn->query($city);
                        if($res->num_rows>0)
                        {
                            echo '<select name="city" id="city" class="form-control" required>';
                            echo '<option value="">Select</option>';
                            while($row=$res->fetch_assoc())
                            {
                                echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
                            }
                            echo '</select>';
                        } else {
                            echo "0 result";
                        }
                    ?>
                </div>

                <div class="form-group">
                    <button type="submit" name="save" id="save" class="btn btn-info" onclick="validate()">Save</button>
                </div>
                </form>
            </div>
            <div class="modal-footer">
            <button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div> 

我在首页中的jquery

    $('.insert_data').click(function(){
                    var vname = $("#name").val();
                    var vmob = $("#mob_no").val();
                    var vdob = $("#dob").val();
                    var vadd = $("#add").val();
                    var vphoto = $("#photo").val();
                    var vgender = $("#gender").val();
                    var vcountry = $("#country").val();
                    var vstate = $("#state").val();
                    var vcity = $("#city").val(); 

                    $.ajax({
                        url:"insert.php",
                        method:"post",
                        data: {
                            name:vname,
                            mob_no:vmob,
                            dob:vdob,
                            add:vadd,
                            photo:vphoto,
                            gender:vgender,
                            country:vcountry,
                            state:vstate,
                            city:vcity
                        },
                        success: function(data){
                            $('#form')[0].reset();  
                            $('#add_data_Modal').modal('hide');  
                            $('#stud_insert').html(data);
                        }
                    });
                });

我的insert.php页面

<?php
include("connection.php");
if(!empty($_POST))
{
    $output = '';
    $name = $_POST['name']);
    $mob = $_POST['mob_no']);
    $dob = $_POST['dob']);
    $add = $_POST['add']);
    $photo = $_FILES['photo']['name']);
    $gender = $_POST['gender']);
    $cn = $_POST['country']);
    $st = $_POST['state']);
    $ct = $_POST['city']);

    $qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
    $row = mysqli_fetch_array($qrycn);
    $country = $row['country_code'];

    $qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
    $row = mysqli_fetch_array($qryst);
    $state = $row['state_code'];

    $qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
    $row = mysqli_fetch_array($qryct);
    $city = $row['city_code'];

    $query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$country', '$state', '$city')";
    if (mysqli_query($conn, $query)) {

                $target_dir="images/";
        $target_file=$target_dir.basename($_FILES["photo"]["name"]);
        $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
        if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
            echo '<script language="javascript">';
            echo 'alert("Image and data Inserted Successfully")';
            echo '</script>';
        }  else {
            echo '<script language="javascript">';
            echo 'alert("Cannot upload")';
            echo '</script>';
        }
    }
    else {
        echo '<script language="javascript">';
        echo 'alert("Cannot insert record")';
        echo '</script>';
    }
    $output .= '<label class="text-success">Data Inserted</label>';
     $output .= '
            <table class="table table-bordered">  
                <tr>  
                     <th>No</th>
                    <th>Name</th>
                    <th>Mobile</th>
                    <th>Birthdate</th>
                    <th>Address</th>
                    <th>Photo</th>
                    <th>Gender</th>
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>

 ';
    $result=  mysqli_query($conn,"select * from stud s, country_master_academic c, master_state st, master_city ct where s.country=c.country_code and s.state=st.state_code and s.city=ct.city_code");
    while($row = mysqli_fetch_array($result))
 {
  $output .= '
        <tr>  
            <td><a href="update.php?no='.$row["stud_no"].'"><button name="edit" value="Edit" style="font-weight:bold;" class="btn btn-warning"><span class="glyphicon glyphicon-edit"></span> Edit</button></a></td>
            <td><button type="submit" style="font-weight:bold;" name="delete" id='.$row["stud_no"].' class="btn btn-danger delete_data"><span class="glyphicon glyphicon-trash"></span> Delete</button></td>
            <td><button type="submit" style="font-weight:bold;" name="view" id='.$row["stud_no"].' class="btn btn-success view_data" data-target="#modalDelete" data-toggle="modal"><span class="glyphicon glyphicon-user"></span> View</button></td>

        </tr>
  ';
 }
 $output .= '</table>';
}
echo $output;
    }

?>

4 个答案:

答案 0 :(得分:3)

请使用您的form ID提交并引导您形成数据并通过ajax并使用alert(data)进行调试。

$(document).ready(function(){
    $("#form").submit(function(event){
        event.preventDefault();
        var formData = new FormData(this);
          $.ajax({
             url: 'insert.php',
             type: 'POST',
             data: formData,
             async: false,
             success: function(data) {
               alert(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
     });
});

答案 1 :(得分:2)

好的,让我列出您html中的所有错误

<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>

删除这样的ID

<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>

并为此添加ID

<input type="date" class="form-control" name="dob" required />

添加ID

<input type="date" class="form-control" name="dob" id="dob" required />

在您的PHP中

$output = '';
$name = $_POST['name']);
$mob = $_POST['mob_no']);
$dob = $_POST['dob']);
$add = $_POST['add']);
$photo = $_FILES['photo']['name']);
$gender = $_POST['gender']);
$cn = $_POST['country']);
$st = $_POST['state']);
$ct = $_POST['city']);

将其更改为

$output = '';
$name = $_POST['name'];
$mob = $_POST['mob_no'];
$dob = $_POST['dob'];
$add = $_POST['add'];
$photo = $_FILES['photo']['name'];
$gender = $_POST['gender'];
$cn = $_POST['country'];
$st = $_POST['state'];
$ct = $_POST['city'];

然后删除

$qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
$row = mysqli_fetch_array($qrycn);
$country = $row['country_code'];

$qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
$row = mysqli_fetch_array($qryst);
$state = $row['state_code'];

$qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
$row = mysqli_fetch_array($qryct);
$city = $row['city_code'];

并将插入内容更改为

$query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct')";

在您的js中,您应该像这样使用FormData()

$('.insert_data').click(function(){
            var vname = $("#name").val();
            var vmob = $("#mob_no").val();
            var vdob = $("#dob").val();
            var vadd = $("#add").val();
            var vphoto = $("#photo").val();
            var vgender = $("#gender").val();
            var vcountry = $("#country").val();
            var vstate = $("#state").val();
            var vcity = $("#city").val(); 
            var fd=new FormData();
            fd.append('name',vname);
            fd.append('mob_no',vmob);
            fd.append('dob',vdob);
            fd.append('add',vadd);
            fd.append('photo',vphoto);
            fd.append('gender',vgender);
            fd.append('country',vcountry);
            fd.append('state',vstate);
            fd.append('city',vcity);
            $.ajax({
                url:"insert.php",
                method:"post",
                data: fd,
                success: function(data){
                    $('#form')[0].reset();  
                    $('#add_data_Modal').modal('hide');  
                    $('#stud_insert').html(data);
                }
            });
        });

答案 2 :(得分:0)

用于插入的新代码: 谢谢你对我的帮助。

import java.util.function.BiPredicate;

public class PredTest {

    public static void main(String[] args) {

        class Fruit {
            public String name;
            public String color;
            Fruit(String name) {this.name = name; }
        };

        class Apple extends Fruit {
            Apple() {super("Apple");}
        };
        class Mango extends Fruit {
            Mango() {super("Mango");}
        };

        BiPredicate<Fruit, ? extends Fruit> tester = (f, nf) -> {
            System.out.println(nf.name);
            return true;
        };
        Fruit f = new Fruit("Not named");
        Apple a = new Apple();
        Mango m = new Mango();

// ########### I see error in the below line
        System.out.println(tester.test(f, m));

    }

}

?>

答案 3 :(得分:0)

这是我在Laravel项目中提交表单数据的代码,如下所示:

//Save new category
$(".frm-add-category").submit(function(event){
    event.preventDefault();
    var formData = new FormData(this);
    $.ajax({
        type:'POST',
        url: '/dashboard/category',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: formData, 
        success:function(data){
            //Refresh the grid
            alert(data.success);
        },
        error: function(e){
          alert(e.error);
        }
    });
});