使用ajax从html表单更新数据库

时间:2022-10-16 13:37:11

I would like some help with ajax. I would like to update a php file which will update a database. I have a form which send the selected check box to a php file which then updates the data base. I would like to do this with ajax but I am struggling with this. I know how to update <div> Html elements by ajax but cannot work this out.

我想要一些关于ajax的帮助。我想更新一个将更新数据库的php文件。我有一个表单,将选中的复选框发送到php文件,然后更新数据库。我想用ajax这样做,但我正在努力解决这个问题。我知道如何通过ajax更新

Html元素,但无法解决这个问题。

HTML script

<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');
?>

I would like this to update with out refreshing the page.

我希望这更新而不刷新页面。

3 个解决方案

#1


1  

I just want some suggestion and first your html page code should like-

我只是想要一些建议,首先你的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>

Now i am turning to php code: You used two line of code right in php

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

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

$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like

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

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

#2


0  

Update: As well as fixing the dataString, stop the form from being submitted so that your function is used:

更新:除了修复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>

The ajax call should handle returned data from updateDb.php.

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

Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:

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

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

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

Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).

更新ajax调用以处理响应并使用params之间的'&'修复dataString(这就是为什么你没有正确获取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")'
    }
}
});

}

#3


0  

document.getElementByName not a javascript function, try document.getElementById() instead

document.getElementByName不是javascript函数,请尝试使用document.getElementById()

You can do this

你可以这样做

<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
}

And you are getting to a post so change the $_GET in you php file to $_POST

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

#1


1  

I just want some suggestion and first your html page code should like-

我只是想要一些建议,首先你的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>

Now i am turning to php code: You used two line of code right in php

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

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

$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like

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

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

#2


0  

Update: As well as fixing the dataString, stop the form from being submitted so that your function is used:

更新:除了修复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>

The ajax call should handle returned data from updateDb.php.

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

Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:

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

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

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

Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).

更新ajax调用以处理响应并使用params之间的'&'修复dataString(这就是为什么你没有正确获取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")'
    }
}
});

}

#3


0  

document.getElementByName not a javascript function, try document.getElementById() instead

document.getElementByName不是javascript函数,请尝试使用document.getElementById()

You can do this

你可以这样做

<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
}

And you are getting to a post so change the $_GET in you php file to $_POST

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