如何使用jquery Ajax传递表单数据以在数据库中插入数据? [英] How to pass form data using jquery Ajax to insert data in database?

查看:48
本文介绍了如何使用jquery Ajax传递表单数据以在数据库中插入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 4 tables namely stud, country_master_academic,master_state and master_city. The main problem is that my form consists of many different fields like textbox, radio buttons, dropdown and an image file, so i am getting really confused. I can't insert data in database. Please help me. I tried many times but its not working. Thanks for the help in advance. Modal in home.php page

 <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

My jquery in home page

    $('.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页面

my insert.php page

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

?>

推荐答案

请使用您的 form id提交并获取表单数据,并通过 ajax 进行调试警报(数据).

Please use your form id submit and get you to form data and pass through ajax and debug with 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
        });
     });
});

这篇关于如何使用jquery Ajax传递表单数据以在数据库中插入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆