-1

I've got the below script included using a .js file and it won't fire. I'm very new to JQuery and can't see where I'm going wrong.

Help please.

I've now changed the script to the below with the following changes: used Theophilus's example code to amend mine and it now fires correctly thanks Julian $(this).attr(':checked') does not work for me as it returns "unasigned." However using .prop does $(this).prop('checked') works as expected (true/false) thanks Rashet, for testing purposes I changed url to '/my.script.php' which contains a simple testing script and still does not work.

if(isset($_POST['id']) || isset($_POST['Purchased'])){
die('Eureka! variables exist');
}else{
die('Failure!, variables do not exist');
}

$('input[name=Purchased]').change(function(){
    //if a checkbox with name 'Purchased' is clicked, do the following.
    var id=$(this).attr('id');  //grab the id from the clicked box
    var Purchased=$(this).prop('checked');

    //alert("ID value:"+id); returns correctly
//  alert("Purchase value:"+Purchased); //Returns correctly

    //setup the ajax call
//Not posting the variable values to PHP processing script
    $.ajax({
        type: 'POST',
        url: '/my.script.php',
        data: {id: 'id',
        Purchased: 'Purchased'}
    });
});
PHP Addict
  • 71
  • 1
  • 9

2 Answers2

1

This should .is(selector) help from this post https://stackoverflow.com/a/12279447/5836034 and you can read up about it here Jquery doc on is() Run code snippet below to see it in action

$('input[name=Purchased]').change(function(){
 
  if (!$(this).is(":checked")) {
        // not checked
    alert("Not Checked");
        return;
    }
  
  alert("Checked continue");
  //check here
  
    //if a checkbox with name 'Purchased' is clicked, do the following.
    var id=$(this).attr('id');  //grab the id from the clicked box
    var Purchased=$(this).val();    //grab the value from the checkbox (remember, if it is checked it will be 'on', else ''

  alert("Purchase value:"+Purchased);

    //setup the ajax call
    $.ajax({
        type: 'POST',
        url: '../../Includes/MyPHP.script.php',
        data: {id: 'id',
        Purchased: 'Purchased'}
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" value="value here" name="Purchased" >
Community
  • 1
  • 1
Theophilus Omoregbee
  • 2,463
  • 1
  • 22
  • 33
0

$(this).val() should be $(this).prop('checked') and it will return true or false.

Jim Ross
  • 65
  • 10
  • Jim I found that $(this).attr(':checked') didn't work however $(this).prop('checked') does. thanks for your help. – PHP Addict Sep 25 '16 at 08:28