我是json的新手,我试图从json发布我的表单值来更新mysql数据库。当我提交时,我有一个成功警报,但是当我查看我的数据库时,似乎我的值没有通过实际传递,使我的大多数字段都空白。需要帮助使用json和php将表单数据传递到我的数据库。
JAVASCRIPT
$('#save').on('click', function () {
$.ajax({
type: "POST",
url: "http://localhost/v_warehouse_1/inc/updateprofile.php",
data: {
detailid: id,
titleid: $('#selectmenu').val(),
name: $('#txtname').val(),
surname: $('#txtsurname').val(),
contact_no: $('#txtcontact_no').val(),
email: $('#txtemail').val(),
category:$('#txtcategory').val(),
package: $('#txtpackage').val(),
password: $('#txtpassword').val()
},
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
alert("Your details we not saved");
} else {
//alert a success message
alert("Details Updated");
location.href='profiledetails.html?id='+id;
}
}
});
});
PHP
require_once("database.php");
$mydb = new MySQLDatabase();
//set varables from json data
$id = json_decode($_POST['detailid']);
$titleid = json_decode($_POST['titleid']);
$name = json_decode($_POST['name']);
$surname = json_decode($_POST['surname']);
$contact_no = json_decode($_POST['contact_no']);
$email = json_decode($_POST['email']);
$category = json_decode($_POST['category']);
$package = json_decode($_POST['package']);
$password = json_decode($_POST['password']);
$mydb->query("UPDATE tblprofile SET title_fk = '$titleid',`name` = '$name',surname = '$surname',contact_no ='$contact_no',email = '$email',category_fk = '$category',package_fk = 'package_fk' ,`password` = 'password' WHERE id = '$id' ;");
$mydb->close_connection();
答案 0 :(得分:1)
无需解码数据。它们将作为普通的发布数据发布。只需访问它们 -
$id = $_POST['detailid'];
答案 1 :(得分:0)
你不需要json_decode来自$ _POST的值。 将代码更改为此
$id = $_POST['detailid'];
$titleid = $_POST['titleid'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$contact_no = $_POST['contact_no'];
$email = $_POST['email'];
$category = $_POST['category'];
$package = $_POST['package'];
$password = $_POST['password'];
虽然你是通过ajax调用发送json但是没有在服务器中编码
答案 2 :(得分:0)
除非您从客户端发送JSON格式的数据,否则请勿使用json_decode()
例如:
在ajax调用中,而不是 data:{}
如果你试图以这种方式发送,
var Jdata = JSON.parse("{'detailid':'"+id+"'");
$.ajax({
type: "POST",
url: "http://localhost/v_warehouse_1/inc/updateprofile.php",
data:Jdata,
datatype: "json",
success: function (status) {
//your stuff..
}
});
然后在php中使用json_decode()