4

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.

5
  • This is what comes up in the URL when I click on a check box and click submit. /ajax.php?niamh=on So the URL is not changing to updateDB.php Commented Sep 14, 2016 at 1:24
  • You are using POST in your ajax call and receiving GET in your php file, why? Commented Sep 14, 2016 at 1:32
  • Originally I was using GET to see what was happening but this did not work so I changed it to POST, Still not working Commented Sep 14, 2016 at 1:33
  • Because if you send POST you have to receive POST, if you send GET you have to receive GET, in your AJAX call and your PHP file, by the way in your PHP file you will get a warning about the header Commented Sep 14, 2016 at 1:37
  • Ok I have tried with POST in both scripts and GET in both scripts but it still not working. its not changing the URL. If I manually type updateDB.php?niamh=on the data base is updated. so the updateDB script is all ok Commented Sep 14, 2016 at 1:39

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this work a treat, Sorry for the late reply got side tracked over the W/E
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")'
    }
}
});

}

2 Comments

Tried the above and still not working. if I replace the place the top script in the updateDB.php script the script stop's working. i have made all POST instead GET and changed the JS to your script. But still when clicking submit the URL becomes ajax.php?boiler=on&niamh=on but I thought it should be updateDB.php?boiler=on&niamh=on cant seem to get this working
Ok so you have the rigth parameters now. Next thing is to stop the form to be submitted so it uses your function: try <form name="form" onsubmit='return false;'>
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.