Mark Buskbjerg Mark Buskbjerg - 6 months ago 30
jQuery Question

Checkbox trouble in jQuery, AJAX and MySQL

I have some trouble sending the value from a variable set with a checkbox to my MySQL database.

Ok.

I have a checkbox, e-mail field and a button:

<label><input type="checkbox" id="emailSubCheck"> Check me</label>

<input type="text" class="form-control email-field" id="emailInput" name="email" placeholder="Your e-mail...">

<button id="sendReportAsMail" class="btn btn-default" type="button">Send</button>


I then run this jQuery (it is the checked variable causing me trouble. It always returns 0 to the database. No matter what I do):

$(document).ready(function() {
var checked;
function checkEmailSub() {

$('#emailSubCheck').click( function() {
if ($('#emailSubCheck').is(':checked')) {
checked = 1;
} else {
checked = 0;
}
});
}
checkEmailSub();

$("#sendReportAsMail").click(function(){

var email = $('#emailInput').val();

$.ajax({
type:"POST",
url:"sendSubmits.php",
data:"email="+email+"&checked="+checked,
success:function(data){
console.log('Ok. So data have been submitted and as I get it. Checked value is now ' + checked);
}
});
});
});


In the log it is perfectly showing 1 if I checked the box before submitting and 0 if I didn't.

This makes me believe that the jQuery (although not perfect) is working.

In my sendSubmits.php I have:

$email=$_POST["email"];
$checked=$POST["checked"];

$sql = "INSERT INTO sendsubmits(email, checked) VALUES ('$email', '$checked')";


(Notice: The DB Connection isn't included. The e-mail is perfectly inserted to the database on every submission. Just the var checked value is missing)

The
checked
column in my MySQL database is INT(1). No matter what i try it just always registers a 0.

What am I doing wrong here?

Thanks a bunch in advance!

Answer

You put the wrong ID in your javascript, try to change the ID of your input like so :

HTML

<label><input type="checkbox" id="emailSubCheck"> Check me</label>

And run the checkEmailSub() function just before making your ajax request to refresh the checked variable.

JAVSCRIPT

$("#sendReportAsMail").click(function(){

var email = $('#emailInput').val();
checkEmailSub(); //Add this to refresh the checked variable.
    $.ajax({
        type:"POST",
        url:"sendSubmits.php",
        data:"email="+email+"&checked="+checked, 
          success:function(data){
          console.log('Ok. So data have been submitted and as I get it. Checked value is now ' + checked);
        }
    });
 });
});

You also forgot the _ in your POST variable, replace this :

PHP

$checked=$POST["checked"];

with this :

$checked=$_POST["checked"];
Comments