[英]Insert data in to database using Jquery .ajax() & PHP is not working
So I am trying to insert data from a form using JQuery .ajax method. 所以我试图使用JQuery .ajax方法从表单插入数据。 In the developer tools I see that the request is send to my process.php file, but I can't add the data to the database.
在开发人员工具中,我看到请求已发送到我的process.php文件,但是我无法将数据添加到数据库中。
Javascript 使用Javascript
$( document ).ready(function() {
console.log( "ready!" );
$("#submit").submit(function(e) {
var url = "process.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: "process.php",
data: $("#submit").serialize(), // serializes the form's elements.
success: function(data){
alert("Data is send successifully!"); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Now I use my custom classes and methods. 现在,我使用我的自定义类和方法。
This is the insert()
method from my db.class.php 这是我的db.class.php中的
insert()
方法
public function insert($fName, $lName, $nickname){
$query = "INSERT INTO users (first_name, last_name, nickname)
VALUES ($fName, $lName, $nickname)";
return $this->_conn->query($query);
}
now I have user.class.php with add()
method 现在我有user.class.php和
add()
方法
public function add($fName, $lName, $nickname){
$db = new db();
$db->insert($fName, $lName, $nickname);
}
Finally a process.php
file. 最后是一个
process.php
文件。 I'm sending my request there. 我正在向我发送请求。
<?php
require_once 'classes/user.php';
require_once 'classes/db.php';
$user = new user();
$user->add($_POST['fName'], $_POST['lName'], $_POST['nickname']);
?>
Try to debug what is in $_POST and make sure that required vars parse to insert query are not empty. 尝试调试$ _POST中的内容,并确保插入查询所需的vars解析不为空。 Try to var_dump($_POST) in process.php and console.log(data) in success statement in java script.
尝试在process.php中的var_dump($ _ POST)和Java脚本中的成功语句中的console.log(data)中。
Your values need to be interpreted as Strings in the SQL-Query, otherwise MySQL will think those are columns and will come up empty. 您的值需要在SQL-Query中解释为String,否则MySQL会认为这些是列,并且将为空。 Here is how you could do that:
这是您可以执行的操作:
public function insert($fName, $lName, $nickname){
$query = "INSERT INTO users (first_name, last_name, nickname)
VALUES ('$fName', '$lName', '$nickname')";
return $this->_conn->query($query);
}
It is generally recommended to use prepared statements to avoid SQL-Injection attacks though. 尽管通常建议使用预处理语句来避免SQL-Injection攻击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.