javascript 如何使用 Jquery 和 Ajax 将 Json 数据发送到数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27997839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send Json data into database using Jquery and Ajax?
提问by geeks
I have made form of customer details form when I click the button, It send Json data to customer. But my code is not inserting data into database. I am new in web technology, please tell me where I am wrong.
当我单击按钮时,我已经制作了客户详细信息表单,它将 Json 数据发送给客户。但是我的代码没有将数据插入数据库。我是网络技术新手,请告诉我我错在哪里。
my Script:
我的脚本:
<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>
form in html
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="[email protected]" 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>
server code
服务器代码
<?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";
}
采纳答案by Anand Patel
Use this
用这个
JavaScript Code:
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 Code
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);
?>
If data is inserted successfully it return true flag with message, otherwise false flag with message
如果数据插入成功,则返回带有消息的真标志,否则带有消息的假标志
回答by archish
try this it might help you.
试试这个它可能会帮助你。
in your ajax function:
在你的 ajax 函数中:
1st change : ContentType:"application/json" to contentType: "application/json; charset=utf-8"
第一个变化:ContentType:"application/json" 到contentType:"application/json; charset=utf-8"
2nd
第二
in data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum} change to data:{type1:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}. see you set type as GET in ajax function so i am thinking that "type" is reserved word, so it might not work. and also check your url where you are sending ajax request if it is correct or not bcoz you are using ip address.
在数据:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum} 更改为数据:{ type1:"booking",Name:uName, Email:mailId, Mob_Num:mobNum}。看到你在 ajax 函数中将 type 设置为 GET 所以我认为“type”是保留字,所以它可能不起作用。并检查您发送ajax请求的网址是否正确,因为您使用的是IP地址。
in your server code i am seeing typo. there is space between
在您的服务器代码中,我看到拼写错误。之间有空间
$_GET ['name'], $_GET ['Email'], $_GET ['Mob_Num'].
$_GET ['name']、$_GET ['Email']、$_GET ['Mob_Num']。
there should be no space so change it to this,
不应该有空间所以把它改成这个,
$_GET['name']
$_GET['姓名']
$_GET['Email']
$_GET['电子邮件']
$_GET['Mob_Num']
$_GET['Mob_Num']
回答by scgough
I would first of all change the "GET" to a "POST" on both the ajax call and the receiving PHP page on the server.
我首先将 ajax 调用和服务器上接收 PHP 页面上的“GET”更改为“POST”。
Secondly, I'd check that the values are actually being passed to the PHP page by using echo to output each of them on the PHP side. That way you'll know at least the values are coming through.
其次,我会通过使用 echo 在 PHP 端输出每个值来检查这些值是否实际上被传递到 PHP 页面。这样你至少会知道这些值正在通过。
JavaScript:
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 Code:
PHP代码:
echo $_POST["type"];
echo $_POST["Name"];
//etc...