tags:

views:

42

answers:

2

Hi folks!

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

A: 

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.

darren102
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
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 Webb-Heller
@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..*)
Gaby
@Gaby: good point.
R0MANARMY
@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.
R0MANARMY
So does this throw an error if the checkbox is not checked?
Rob
+1  A: 

.is(':checked') should work

Rob