1

I have an AJAX call in my jQuery/PHP app. It needs to send some data to a PHP script to process (I have this part working fine).

My jQuery variable:

var form_data = {
   urltitle: '<?php echo $urltitle; ?>',
   subscribe: $('#subscribe').val(),
   comment: $('#commentbox').val()
};

This works fine, the PHP script reads the values of all the variables - except for the 'subscribe' variable. Subscribe is a checkbox, like so:

<input type="checkbox" name="subscribe" checked="checked" value="subscribe" id="subscribe"/> 

How can I pass the 'value' of the checkbox to my PHP script? I have a non-AJAX version of this script too, which is almost identical, except on the PHP side I use:

if (isset($_POST['subscribe'])) { /* do something */ }

And that works fine...

Thanks!

Jack

Jack
  • 9,615
  • 18
  • 72
  • 112
  • Possible duplicate [Jquery - Check if checkbox is checked](http://stackoverflow.com/questions/2204250/jquery-check-if-checkbox-is-checked) – Roman Jun 29 '10 at 14:49

2 Answers2

1

When you say value do you mean subscribe or do you just want to know if the checkbox has been checked or not.

If you just want to know if it has been checked then you can do $('#subscribe:checked').val() and if it is null then you know it is not checked and if it is not then you should have the value in your case subscribe.

Roman
  • 19,581
  • 6
  • 68
  • 84
darren102
  • 2,830
  • 1
  • 22
  • 24
  • If subscribed is unchecked then .val() will be "undefined" won't it? it'd be like calling .val() on a zero-length jQuery result. – Famous Nerd Jun 29 '10 at 14:45
  • Cheers Darren, this did the trick. Famous Nerd, I realise that it would be undefined if unchecked, but my PHP simply reads if (isset($_POST['subscribe'])) { do something } else { do something else }. So it doesn't need to check if it's 'undefined'. But, thank you :) – Jack Jun 29 '10 at 14:50
  • @R0MANARMY, actually yes. Because @Famous Nerd, is commenting on @darren102 answer who says that `$('#subscribe:checked').val()` would return null .. it would return `undefined` (*notice that he is asking the value of the checked #subscribe .. so if it is not checked it will return no jquery object..*) – Gabriele Petrioli Jun 29 '10 at 14:51
  • @Jack Webb-Heller: BTW, although this way works, it's a really roundabout way of accomplish things, and there are more straight forward ways that I would recommend using. – Roman Jun 29 '10 at 15:08
1

.is(':checked') should work

Rob
  • 1,865
  • 1
  • 14
  • 26