如何使用 Jquery 和 Ajax 将 Json 数据发送到数据库?

How to send Json data into database using Jquery and Ajax?

当我点击按钮时,我已经制作了客户详细信息表格,它向客户发送 Json 数据。但是我的代码没有将数据插入数据库。我是网络技术的新手,请告诉我哪里错了。

我的脚本:

 <script>   
    $(document).ready(function(){              
            $("#btnBooking").on("click", function(){                   

                var uName = document.getElementById('userName').value;        
                var mailId = document.getElementById('addressemailId').value;           
                var mobNum = document.getElementById('userContactNumber').value;                    
                $.ajax({
                    url:"http://192.168.1.11/customerhomes/customer.php", 
                    type:"GET", 
                    dataType:"json", 
                    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}, 
                    //type: should be same in server code, otherwise code will not run
                    ContentType:"application/json", 
                    success: function(response){ 
                            alert("13");                                                 
                        }, 
                        error: function(err){ 
                        alert(JSON.stringify(err)); 
                    } 
                })              
            }); 
    });
</script>

表格在html

<body>
    <div class="page-header text-center">
        <form >
            <div class="col-lg-8">                                  
                <div class="form-group">
                        <label class="col-lg-3 control-label">Name:<font style="color: red;">*</font></label>
                        <div class="col-lg-9">
                            <input type="text" class="form-control" id="userName" name="userName" placeholder="Full Name" value="">
                        </div>
                </div>


                <div class="form-group">
                    <label class="col-lg-3 control-label">Mobile:<font style="color: red;">*</font></label>
                    <div class="col-lg-9">
                        <input type="text" class="form-control" id="userContactNumber" name="userContactNumber" type="number" placeholder="" onkeypress="enableKeys(event);" maxlength="10" placeholder="9966778888">
                    </div>
                </div>

                <div class="form-group">
                        <label class="col-lg-3 control-label">Email:<font style="color: red;">*</font></label>
                        <div class="col-lg-9">                                  
                            <input type="text" class="form-control" name="addressemailId" id="addressemailId" placeholder="you@example.com" value="">
                        </div>
                </div>  
                <div class="form-group marg-bot-45">
                    <label class="col-lg-3 control-label"></label>
                    <div class="col-lg-9">

                        <a href="" class="btn btn-info"  id="btnBooking">Confirm Booking</a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>

服务器代码

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("customer_details");
if(isset($_GET['type']))
{
    if($_GET['type']=="booking"){
        $name = $_GET ['Name'];
        $mail = $_GET ['Email'];
        $mobile = $_GET ['Mob_Num'];
        $query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mail','$mobile')";
        $result1=mysql_query($query1);
    }
}
else{
    echo "Invalid format";
}

首先,我会在服务器上的 ajax 调用和接收 PHP 页面上将 "GET" 更改为 "POST"。

其次,我通过使用 echo 在 PHP 端输出每个值来检查这些值是否实际传递到 PHP 页面。这样你至少会知道值是通过的。

JavaScript:

var uName = $('#userName').val();        
var mailId = $('#addressemailId').val();           
var mobNum = $('userContactNumber').val();                    
$.ajax({
    url:"http://192.168.1.11/service4homes/customer.php", 
    type:"POST", 
    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}, 
    complete: function(response){ 
        var test = $.parseHTML(response);
        alert(test);
    }
 });

PHP代码:

echo $_POST["type"];
echo $_POST["Name"];
//etc...

使用这个

JavaScript代码:

<script>
        $(document).ready(function(){
            $("#btnBooking").on("click", function(e){

                // as you have used hyperlink(a tag), this prevent to redirect to another/same page
                e.preventDefault();

                // get values from textboxs  
                var uName = $('#userName').val();
                var mailId = $('#addressemailId').val();
                var mobNum = $('#userContactNumber').val();

                $.ajax({
                    url:"http://192.168.1.11/customerhomes/customer.php",
                    type:"GET",
                    dataType:"json",
                    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum},
                    //type: should be same in server code, otherwise code will not run
                    ContentType:"application/json",
                    success: function(response){
                        alert(JSON.stringify(response));
                    },
                    error: function(err){
                        alert(JSON.stringify(err));
                    }
                })
            });
        });
    </script>

PHP代码

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
 mysql_connect("localhost","root","1234");
 mysql_select_db("customer_details");
if(isset($_GET['type']))
{
    $res = [];

    if($_GET['type'] =="booking"){
        $name  = $_GET ['Name'];
        $mail  = $_GET ['Email'];
        $mobile  = $_GET ['Mob_Num'];
        $query1  = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mail','$mobile')";
        $result1 = mysql_query($query1);

        if($result1)
        {
            $res["flag"] = true;
            $res["message"] = "Data Inserted Successfully";
        }
        else
        {
            $res["flag"] = false;
            $res["message"] = "Oppes Errors";
        }

    }
}
else{
    $res["flag"] = false;
    $res["message"] = "Invalid format";
}

    echo json_encode($res);
?>

如果数据插入成功 return true flag with message,否则 false flag with message

试试这个可能对你有帮助。

在您的 ajax 函数中:

第一个变化: 内容类型:"application/json" 到 内容类型:"application/json; charset=utf-8"

第 2

in data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum} 改为data:{type1:"booking" ,姓名:uName,Email:mailId,Mob_Num:mobNum}。看到你在 ajax 函数中将类型设置为 GET,所以我认为 "type" 是保留字,所以它可能不起作用。并检查您的 url 发送 ajax 请求是否正确,因为您使用的是 ip 地址。

在你的服务器代码中我看到了拼写错误。

之间有 space

$_GET ['name'], $_GET ['Email'], $_GET ['Mob_Num'].

应该没有space所以改成这样,

$_GET['name']

$_GET['Email']

$_GET['Mob_Num']