1
<html>
<body>
<input type="checkbox" checked="checked">
</body>
</html>

I want to pass the value of the checkbox as 1 or 0 according to selection. If it is checked then 1 is sent to a PHP file else 0 is sent. The value is sent using a onClick event in the html, using AJAX I want to send the value.

I'm new to AJAX so unable to figure out a way to accomplish this task.

Thanks in advance.

6
  • I know that, but I don't know how to do it. Commented Nov 9, 2012 at 4:22
  • 1
    No i was asking you want the solution in jquery ? Commented Nov 9, 2012 at 4:23
  • It might be easier to change this on the PHP side (if at all possible)... Commented Nov 9, 2012 at 4:23
  • 1
    I'm pretty sure jquery page for .get gives you examples of how to do this. Commented Nov 9, 2012 at 4:24
  • 2
    I disagree the question is trival and answer is easily searched for. Commented Nov 9, 2012 at 4:38

3 Answers 3

3
$(document).ready(function(){
  $('body').delegate('#Yourbuttonid','click',function(){
        var chkval = 0
          if($('#yourcheckboxid').is(':checked')){
            chkval  = 1;
          }
   $.ajax({
       url: "Your_url",
       type: "POST",
       data:{'checkboxvalue':chkval},

       success:function(returndata){


       },error:function(errordata){


       }
     });

   });  

});

and in your Php file

You can get the checkbbox value as echo $_POST['checkboxvalue'];

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

1 Comment

This script is not working. When i check the checkbox, no data get sent.
2

try

$('element').on('click', function(){
$checkbox = $(':checkbox').prop('checked');
​$.post({ 
          url :'PageWhereYouWanToSend.php'​​​​​​​​​​​​​​​​​​​​​​​​​​,
          data : {​ 'checked' : $checkbox },
          success : function (resp){
                     alert(resp);
                   }
      });
​});​

References:

.prop

.post

.on

4 Comments

You used on here and the depreciated live in my Edit O_o ? :)
` data : {​ checked : $checkbox },` in here i think checked needs to be in quotes
because were are using .click, so i changed to .live , it is better than that. If i changes to .on then you may disagree. thats why :)
Anyway live is way too depreciated i welcome delegate` :) :) anyway thanks man !
1
var subcheck = 0;
$('input:checkbox').change(function(){
   if($(this).is(':checked')){
      subcheck = 1;
   } else {
      subcheck = 0;
   }


   $.post("your.php", { checkdata: subcheck},
   function(data) {
      //your code here
   });
});

1 Comment

You left .post outside of the .change function so the change would never be posted.

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.