简体   繁体   中英

update database from html form using ajax

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.

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.

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

<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

$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

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

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

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

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:

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) .

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

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM