【问题标题】:update database from html form using ajax使用ajax从html表单更新数据库
【发布时间】:2016-09-14 01:20:49
【问题描述】:

我想要一些关于 ajax 的帮助。我想更新一个将更新数据库的 php 文件。我有一个表单,它将选定的复选框发送到一个 php 文件,然后更新数据库。我想用 ajax 来做这件事,但我正在为此苦苦挣扎。我知道如何通过 ajax 更新 <div> Html 元素,但无法解决。

HTML 脚本

<html>
<head>
    <script src="jquery-3.1.0.min.js"></script>
</head>

<body>
<form name="form">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
    var boiler = document.getElementByName("boiler").value;
    var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'boiler=' + boiler + 'niamh=' + niamh;

// AJAX code to submit form.
    $.ajax({
    type: "POST",
    url: "updateDB.php",
    data: dataString,
    cache: false,
    success: function() {
        alert("ok"); 
    }
    });
}

</script>
</body>
</html>

PHP updateDB.php

<?php

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="14Odiham"; // Mysql password 
$db_name="heating"; // Database name 
$tbl_name = "test";

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;

// Insert data into mysql 
$sql = "UPDATE $tbl_name SET boiler=$boiler WHERE id=1";
$result = mysql_query($sql);

// if successfully insert data into database, displays message "Successful". 
if($result){
echo "Successful";
echo "<BR>";
}

else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
header ('location: /ajax.php');
?>

我希望在不刷新页面的情况下进行更新。

【问题讨论】:

  • 这是当我单击复选框并单击提交时 URL 中出现的内容。 /ajax.php?niamh=on 所以 URL 不会更改为 updateDB.php
  • 您在 ajax 调用中使用 POST 并在 php 文件中接收 GET,为什么?
  • 最初我使用 GET 来查看发生了什么,但这不起作用,所以我将其更改为 POST,仍然无法正常工作
  • 因为如果你发送 POST 你必须接收 POST,如果你发送 GET 你必须接收 GET,在你的 AJAX 调用和你的 PHP 文件中,顺便在你的 PHP 文件中你会收到一个警告关于标题
  • 好的,我已经尝试在两个脚本中使用 POST 并在两个脚本中使用 GET,但它仍然无法正常工作。它不会更改 URL。如果我手动键入 updateDB.php?niamh=on 数据库就会更新。所以updateDB脚本一切正常

标签: php html ajax


【解决方案1】:

我只是想要一些建议,首先你的 html 页面代码应该喜欢-

<html>
<head>
    <script src="jquery-3.1.0.min.js"></script>
</head>

<body>
<form name="form" id="form_id">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
   // it's like cumbersome while form becoming larger  so comment following three lines        
      // var boiler = document.getElementByName("boiler").value;
     // var niamh = document.getElementByName("niamh").value;
     // Returns successful data submission message when the entered information is stored in database.
    //var dataString = 'boiler=' + boiler + 'niamh=' + niamh;

// AJAX code to submit form.
    $.ajax({
    // instead of type use method
    method: "POST",
    url: "updateDB.php",
    // instead  dataString i just serialize the form like below this serialize function bind all data into a string so no need to worry about url endcoding
    data: $('#form_id').serialize(),
    cache: false,
    success: function(responseText) {
        // you can see the result here
        console.log(responseText)
        alert("ok"); 
    }
    });
}

</script>
</body>
</html>

现在我转向 php 代码: 你在 php 中使用了两行代码

$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;

$_GET 用于 get 方法,$_POST 用于 post 方法,因此您在 ajax 中使用 post 方法,上面的代码行应该是这样的

$boiler = (isset($_POST['boiler'])) ? 1 : 0;
$niamh = (isset($_POST['niamh'])) ? 1 : 0;

【讨论】:

  • 感谢这项工作的款待,很抱歉迟到的回复被 W/E 跟踪了
【解决方案2】:

更新: 除了修复 dataString,停止提交表单以便使用您的函数:

<form name="form" onsubmit="return false;">
    <input type="checkbox" id="boiler" name="boiler">
    <input type="checkbox" id="niamh" name="niamh">
    <button onclick="myFunction()">Update</button>
</form>

ajax 调用应该处理从 updateDb.php 返回的数据。

更新 php 文件以将数据发送回服务器,恢复为 $_POST 而不是 $_GET 并删除底部的标头调用:

if($result){
    $data['success'=>true, 'result'=>$result];

} else {
    $data['success'=>false];
}
echo json_encode($data);
// die(); // nothing needed after that

更新 ajax 调用以处理响应并在参数之间使用“&”修复您的 dataString(这就是您没有正确获取参数的原因)

var dataString = 'boiler=' + boiler + '&niamh=' + niamh;

// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function(data) {
    var json = $.parseJSON(data);
    if(json.success){
        // update the page elements and do something with data.results
        var results = data.results;

    } else {
        // alert("some error message")'
    }
}
});

}

【讨论】:

  • 试过以上方法还是不行。如果我替换 updateDB.php 脚本中的顶部脚本,则脚本停止工作。我已将所有 POST 改为 GET 并将 JS 更改为您的脚本。但是当单击提交时,URL 仍然变为 ajax.php?boiler=on&niamh=on 但我认为它应该是 updateDB.php?boiler=on&niamh=on 似乎无法正常工作
  • 好的,你现在有了正确的参数。接下来是停止要提交的表单,以便它使用您的功能:尝试
【解决方案3】:

document.getElementByName 不是 javascript 函数,请尝试 document.getElementById() 代替

你可以这样做

<form name="form" onsubmit="myfunction()">
   <input type="checkbox" id="boiler" name="boiler">
   <input type="checkbox" id="niamh" name="niamh">
   <input type="submit" value="Update"/>
</form>

Javascript:

function myFunction() {
var boiler = document.getElementById("boiler").value;
var niamh = document.getElementById("niamh").value;
// Returns successful data submission message when the entered information is stored in database.

// i dont practice using url string in ajax data as it can be compromised with a quote (') string, instead i am using json

// AJAX code to submit form.
    $.ajax({
    type: "POST",
    url: "updateDB.php",
    data: {
       boiler: boiler,
       niamh: niamh
    },
    cache: false,
    }).done(function() {
        alert('success');
    }); // i do this because some jquery versions will deprecate the use of success callback
}

你正在发帖,所以将你的 php 文件中的 $_GET 更改为 $_POST

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多