0

I really can't believe something so simple is causing such a headache.

<input type='checkbox' name="phoneConsent" id="phoneConsent" value="1">

Whether or not this checkbox is checked, it still posts the value "1" for phoneConsent -- shouldn't it not be posting anything?

I think this is the problem:

// variables for data
$(this).find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

        // load loaded variables into array
        form_data[name] = value;


    });

how can I specify that checkboxes that are not set shouldn't have their values posted?

php:

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

        // Set up the data that is headed to the table
        $data = Array(               
            'phoneConsent'   => $phoneConsent
        );

the actual HTML

<div class = "form-group">
                <label for="phoneConsent" class='checkbox-inline <?php echo ($this_user[0]['subscription'] == 1 ? '' : 'disabledClass') ;?>'>
                    <input type='checkbox' name="phoneConsent" id="phoneConsent" value="1" <?php echo ($this_user[0]['phoneConsent'] == 1 ? ' checked ' : '') ;?> <?php echo ($this_user[0]['subscription'] == 1 ? '' : ' disabled ') ;?>>
                    Premium account holders: check this box to post your phone number to your teaching profile.
                </label>
            </div>

entire HTML form

<form method="post" class = "multi-form teacher_account_form" id="personal_form" name="personal_form">
            <div class ="form-group">
                <label for="country">What country are you from?</label>
                <!-- for selecting the country from db -->
                <div id = "countryfromdb" class = "hidden"><?=$this_user[0]['country_prefix'];?></div>
                <?php $form->select("country", "country_list") ;?>
            </div>

            <div class = "form-group">
                <label for="chinese_name">What is your Chinese name?</label>
                <input type = "text" class="form-control" name="chinese_name" id="chinese_name" value="<?=$this_user[0]['chinese_name']?>">
            </div>
            <div class = "form-group">
                <label for="phone">What is your phone number?*</label>
                <input type="text" class="form-control bfh-phone" data-format="+86 ddd dddd dddd" name="phone" id="phone" value="<?=$this_user[0]['phone']?>">
            </div>
            <div class = "form-group">
                <label for="phoneConsent" class='checkbox-inline <?php echo ($this_user[0]['subscription'] == 1 ? '' : 'disabledClass') ;?>'>
                    <input type='checkbox' name="phoneConsent" id="phoneConsent" <?php echo ($this_user[0]['phoneConsent'] == 1 ? ' checked ' : '') ;?> <?php echo ($this_user[0]['subscription'] == 1 ? '' : ' disabled ') ;?>>
                    Premium account holders: check this box to post your phone number to your teaching profile.
                </label>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-default btn-med account_submit" id="personal_submit" name="personal_submit">Update Personal</button>
            </div>
            <small style="color:red;">*Your phone number will NOT appear on your public profile without your permission.</small>
        </form>

jQuery

  var which_button;
//$('.account_submit').click(function() {
$('form.teacher_account_form').on('submit', function(e) {
    e.preventDefault();
    which_button = $(this).attr('id');

    // Create empty jQuery objects -
    var $jsOutput = $([]);
    var $jsForm = $([]);

    // url to submit to
    var ajaxURL = "/users/p_teacher_account_work";

    // Assign jQuery selector objects
    switch (which_button) {
        case "pay_form":
            $jsOutput = $('#pay_output');
            $jsForm = $('#pay_form');
            break;
        case "edu_form":
            $jsOutput = $('#edu_output');
            $jsForm = $('#edu_form');
            break;
        case "image_form":
            $jsOutput = $('#image_output');
            $jsForm = $('#image_form');
            break;
        case "personal_form":
            $jsOutput = $('#personal_output');
            $jsForm = $('#personal_form');
            break;
    }

    // empty data object
    var form_data = {};

    // variables for data
    $(this).find('[name]').each(function(index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        // load loaded variables into array
        form_data[name] = value;


    });

    $.ajax({
        type: 'post',
        url: ajaxURL,
        data: form_data,
        beforeSend: function() {
            //Display a loading message while waiting for the ajax call to complete
            $jsOutput.html("Updating...");
        },
        success: function(response) {
            $jsOutput.html(response);
        }

    });

    return false;


});

console.log form output

checkbox checked

 Object {country: "AI", chinese_name: "", phone: "+86 1", phoneConsent: "on", personal_submit: ""} teacher_account.js:130

checkbox unchecked

Object {country: "AI", chinese_name: "", phone: "+86 1", phoneConsent: "on", personal_submit: ""} teacher_account.js:130

Code finally works. I am very grateful. UPDATED jQuery:

$(this).find('[name]').each(function(index, value) {
        var that = $(this);
        if(that.is(':checkbox'))
        {
            if(that.is(':checked'))
            {
                var name = that.attr('name');
            }
        }
        else
        {
            name = that.attr('name');
        }
            var value = that.val();

        // load loaded variables into array
        form_data[name] = value;


    });
9
  • i just pasted your code on my server and it works like a charm check it by yourself robyapps.com/prova.php i just had to remove the country select method since i didn't have that php function Commented Apr 4, 2014 at 21:57
  • @verdesrobert maybe we should trade computers, I'm ready to throw mine out the window Commented Apr 4, 2014 at 22:11
  • Put print_r($_POST); in your php to see what you receive Commented Apr 4, 2014 at 22:13
  • @verdesrobert since its AJAX, I printed my form data to the console. I just added the console outpout above: unlike on your server, on mine, whenever I submit the form, it posts the checkbox whether it is checked or not Commented Apr 4, 2014 at 22:17
  • What Version of jquery are you using? In My page i used the google latest jquery Version maybe that makes a difference Too Commented Apr 4, 2014 at 22:21

3 Answers 3

1

The problem is in your jQuery .ajax() handler. In a "natural" form submit, the checkbox would not be posted, but you are doing the post yourself via ajax after having collected the form data yourself.

In this:

// variables for data
$(this).find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

    // load loaded variables into array
    form_data[name] = value;
});

You are selecting everything that has a ['name'] and assigning its value on form_data[]
The checkbox does have both a name and a value, so you are putting the name:value pair in form_data whether or not the box is checked.

Immediately after, you do:

    $.ajax({
        type: 'post',
        url: ajaxURL,
        data: form_data,
     ...(etc)

where you are sending the data: form_data as the post body, which includes the checkbox "phoneConsent:1" pair.

To avoid this, you'll have to process the controls a bit smarter, check the input control type and send checkbox (or radiobutton) data only when the control is checked.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much -- i completely agree -- any idea how i might only send checked inputs?
If you browse the code of the page i sent you Will see that that's not the problem
any idea how to keep my method of assigning name/value pairs to the JS object, but now being able to process multiple checkboxes that are part of the same name, "checkbox[]". ? Since I assign a value to a name, I only get the final checkbox of the same name being posted.
0

Try this block of code:

<html>
<head>
<title></title>
</head>
<?
if(isset($_POST['phoneConsent'])){
echo $_POST['phoneConsent'];
}
?>
<body bgcolor="#FFFFFF">
  <form method="post" action="test.php">
    <input type='checkbox' name="phoneConsent" id="phoneConsent" value="1">
    <input type="submit" />
  </form>
</body>


</html>

I think you have a problem somewhere else than in this part of your html.

Comments

0

You check if the value is set, not the value itself. It will be sent no matter if it's unchecked or not as far as I remember.

Change $phoneConsent = (isset($_POST['phoneConsent'])) ? 1 : 0;

to if(isset($_POST['phoneConsent'])) $phoneConsent = $_POST['phoneConsent']) == '1' ? 1 : 0;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.