Thursday, April 28, 2011

AJAX checkbox if statement

I've got a bunch of variables being pulled from form ID's before being sent in a query string to a PHP. However, as one input is a checkbox I'm trying to get AJAX to set the variables value according to whether it's checked or not. i.e..

 if (document.getElementById('bold').checked) { var bold = "true"; 
 }
 else { var bold = "false"; }

But, it doesn't actually send anything to the PHP. I'm guessing syntax a lot of the time, so if anyone can correct I'd be most grateful.

From stackoverflow
  • As long as you've given it a name it should be accessible as "on" or "off" in the backend e.g.

    var $checked = $_POST["checkboxname"] == "on";
    

    So your javascript is redundant.

    WiseDonkey : Ideally, this would the answer but it's being sent in a GET and the string literally just has bold=true or bold= and nothing there. I tried using isset() or empty()... neither would work. I think it needs to be sorted in the JS.
    Rob Stevenson-Leggett : Can't you just do var $isBold = $_GET["bold"] == "true" then?
  • Firstly, instead of: var bold = "true";

    I think you're actually looking for something like: document.getElementById('bold').value = "true";

    Secondly, if the checkbox is not checked nothing will be sent to the PHP script (unchecked checkboxes are not sent as part of a form submission).

    WiseDonkey : Didn't work on that as I have to still declare the var afterwards. Secondly, normally that is the case but this is submitted by an ajaxFunction onChange of anything. So the value does seem to be submitted whatever the cirumstances.
    Narcissus : If that's the case then I agree with chosta... we need to see the sending code.
    DaNieL : Agree, if the checkbox isnt checked, nothing will be send with the form
    WiseDonkey : Thanks very much, I've actually identified the 'ahem' problem... PHP side the variable was typo'd out. The proposed method I used in the question has worked. :/ Sorry to faff you around guys, thanks for the effort.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.