[英]Pass data from JQuery to database via Javascript/AJAX/JSON/PHP
I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model.我正在尝试通过使用 MVC 模型使用 JQuery、AJAX/JSON 和 PHP 从我的 HTML 代码向我的数据库添加数据。 Below is a small sample of what I am looking to achieve.
以下是我希望实现的目标的一小部分示例。
In my front end I have a checkbox with different options and a button named 'Add'.在我的前端,我有一个带有不同选项的复选框和一个名为“添加”的按钮。 The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON.
从这里选择的元素由我已经正确测试过的 Javascript 函数拾取,完成后我调用另一个 Javascript 函数来执行 AJAX/JSON。 What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
我仍然对将数据发送到 PHP 的实际 AJAX/JSON 过程感到新鲜。
My Javascript function:我的 Javascript 函数:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:我的 PHP 函数:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.请注意,add_fruits() 函数负责对数据库执行查询,我没有在此处包含它,因为它与我的问题无关。
Just do echo
in your PHP:只需在您的 PHP 中
echo
显:
PHP PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.