Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Check if check box is checked using PHP and AJAX

Hi I am trying to know whether the checkbox is checked so I can display a message and if not another message will got displayed. I tried several times and it didn't work. It will just alert True when I check and uncheck.

AJAX code:

            $('#check').click(function(){
                var check= $(this).val();

                $.ajax({
                    url: './opt/index_opt.php',
                    type: 'POST',
                    data: {check:check},
                    success: function(data){
                        alert(data);
                    }
                });
            });

This is my PHP file:

<?php
    session_start();
    include "../db.php";
    $user= $_SESSION['id'];
    if(isset($_POST)){
        $check = $_POST['check'];
        if(isset($check)){
            echo 'True';
        }else{
            echo 'False';
        }
    }
?>

7 Answers

Michael Collins
Michael Collins
433 Points

Okay, here's a working example. The first part is the HTML page with the form and the JavaScript.

<html>
<head>
<title>Untitled Document</title>

<script language="javascript" src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>

<script language="javascript" type="text/javascript">

send_data = function(name) {

        $.ajax({
      url: "/test/index.php",
            dataType: "json",
            data: {'name' : name},
            type: "POST",
            cache: false

    }).done(function(data, status, xml) {

         var obj = jQuery.parseJSON(data);
         alert(obj.success);

        }).fail(function(jqXHR, textStatus, errorThrown) {


        }).always(function() {


        });

}


$(document).ready(function() {

    $("#myform").submit(function() {

        var cb = $("input#firstname");

        if (cb.is(":checked")) {
            send_data(cb.val());
        } else {
            alert("not sending data - box is not checked");
        }
        return false; 
    });

});
</script>

</head>
<body>

<form id="myform" action="">
Check this box if your first name is Fred: 
<input type="checkbox" id="firstname" name="firstname" value="Fred" />
<input type="submit" value="Submit" />

</form>
</body>
</html>

The second part is the PHP script.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  if (isset($_REQUEST['name'])) {

  # Append something onto the $name variable so that you can see that it passed through your PHP script.
   $name = $_REQUEST['name'] . ' - 123 ';

    # I'm sending back a json structure in case there are multiple pieces of information you'd like
    # to pass back.
    header('Content-Type: application/json');
    print json_encode('{"success" : "' . $name . '"}');

    }

}

exit;

?>

Now its working thank you :)

Michael Collins
Michael Collins
433 Points

I wonder if you are using "check" a few too many times. You are initializing it as a variable but then also using is an object property. I'm thinking you could either change the name of the value your are retrieving from "check" to value. OR, you could enclose the data object in quotes, like this

data:{"check":check}

Try changing your value name so as to clarify which variable is holding which data and see if that doesn't move you farther along.

$('#check').click(function(){
                var value= $(this).val();
                $.ajax({
                    url: './opt/index_opt.php',
                    type: 'POST',
                    data: {check:value},
                    success: function(data){
                        alert(data);
                    }
                });
            });

I tired it, it didn't work

Michael Collins
Michael Collins
433 Points

Ah, the checkbox always has the same value, whether it's checked or not.

I think you want to check whether the check box is checked. var value = $('#checkbox').is(':checked');

$('#check').click(function(){
                var value= $(this).is(':checked');
                $.ajax({
                    url: './opt/index_opt.php',
                    type: 'POST',
                    data: {check:value},
                    success: function(data){
                        alert(data);
                    }
                });
            });

When I added $(this).is(':checked'); It just displays false.

Michael Collins
Michael Collins
433 Points

Would you display your HTML code too please?

<input type="checkbox" name="check"  id="check" checked >
Michael Collins
Michael Collins
433 Points

isset() returns TRUE when a variable exists even if the value it holds is empty -> "" it only returns false when the value is set to NULL. NULL is not the same as empty.

You don't have to put a value in the checkbox, but if you don't I believe it is by default the integer 1. So, your HTML means you assigned a value of 1. And, in PHP, 1 is the same as TRUE.

<input type="checkbox" name="check"  id="check" check="checked" value="1">

Once you assigned $check = $_POST['check'], you ended up setting $check to the empty set "" which isset() will return true.

Try this ...

<?php
    session_start();
    include "../db.php";
    $user= $_SESSION['id'];
    if(isset($_POST)){
        $check = $_POST['check'];
        if($check == 1){
            echo 'True';
        }else{
            echo 'False';
        }
    }
?>

It still only shows false. Really thank you for trying to help me

Michael Collins
Michael Collins
433 Points

Alright, I'll get back to you tomorrow. I thought I could just glean real quick what's going on but I'm obviously flubbing it. I'll have time tomorrow morning to make a working example. So, if someone else hasn't given you some direction by then, I'll get back to you.

Okay no problem thank you