使用ajax

时间:2016-09-14 01:20:50

标签: php html ajax

我想帮助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');
?>

我希望在刷新页面时更新。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

更新: 除了修复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调用以处理响应,使用'&amp;'修复dataString params之间(这就是你没有正确使用params的原因)

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")'
    }
}
});

}

答案 2 :(得分:0)

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