Omar Taha
Omar Taha

Reputation: 265

Submit form using javascript and receive it from other page

I'm trying to submit a form to a PHP page, but the data is not accessible from this page, This is my code:

Html code:

<form method="post" id="formid" action="test.php">
    <input type="hidden" name="going" id="going" value="" /> 
</form>

Javascript:

$("#ongoing").change(function() {
    var ongoing = $(this).attr('checked');
    var input = document.getElementById('going');
    var form = document.getElementById('formid');

    if (ongoing)
        input.value = "1";
    else
        input.value = "0";

    form.submit();
});

test.php

if(isset($_POST['going']))
      echo $_POST['going'];

What am I doing wrong?

Upvotes: 0

Views: 87

Answers (2)

rollingcodes
rollingcodes

Reputation: 15978

Try this! It does what you want with much less code. You were having issues because the checked attribute returns a string not a boolean value.

$("#ongoing").change(function() {
    var form = document.getElementById('formid');
    form.going.value = $(this).attr('checked').toLowerCase() == "checked" ? "1" : "0";
    form.submit();
});

The longer way looks like:

$("#ongoing").change(function() {
    var form = document.getElementById('formid');
    var input = document.getElementById('going');
    var isChecked = $(this).attr('checked').toLowerCase() == "true";
    if(isChecked)
        input.value = "1";
    else
        input.value = "0";
    form.submit();
});

Additionally! It is good practice when writing html attributes to always type checked="true" (or "false") even though just checked is synonymous with the previous. Unpaired markup attribute-values could be mistaken by amateur coders as tag names.

See here for more Checkboxes in Jquery

Upvotes: 0

Satish Sharma
Satish Sharma

Reputation: 9635

use this

   $("#ongoing").change(function() {
        var input = document.getElementById('going');
        var form = document.getElementById('formid');

       if($(this).is(':checked'))
       {
          input.value = "1";
       }
       else
       {
          input.value = "0";
       }

        form.submit();
    });

Upvotes: 1

Related Questions