My code calls an ajax script when a button is clicked. The ajax script is just returning a 0 or 1 at this point like this:
$result = 1;
echo json_encode($result);
The problem is with this line:
$('.adt-checkbox_0')[0].prop("checked", result);
It gives the error
TypeError: $(...)[0] is undefined; can't access its "prop" property
The code seems to work but it looks like it runs twice since I get failures occasionally (error messages in the php code). If I remove the [0], as I've seen in some posts, the error goes away but the script doesn't work. I added the code below in jsfiddle but it doesn't work, I guess, due to the php function. Can someone explain what is wrong with that statement? Should I have a line checking if it exists? If so, how do I do that?
<form>
<tr>
<input type="hidden" name="pid-adt-checkbox_0" value="14" id="pid-adt-checkbox_0" />
<td class="adt" id="adt-checkbox_0"><input type="checkbox" name="adt_check_0" /></td>
</tr>
<tr>
<input type="hidden" name="pid-adt-checkbox_1" value="15" id="pid-adt-checkbox_0" />
<td class="adt" id="adt-checkbox_1"><input type="checkbox" name="adt_check_1" /></td>
</tr>
</form>
<script>
$(".adt").click(function(){
var next_id = $(this).closest('td').attr('id') ;
var pid_id = 'pid-'+next_id;
var pid = $("#"+pid_id).val();
var dataArray = {};
dataArray[0] = 'change_status';
dataArray[1] = 'oID';
dataArray[2] = pid;
$.ajax({
type: 'POST',
data: dataArray ,
async: false,
url:"adt_ajax.php",
dataType: 'json',
success:function(result) {
$('.adt-checkbox_0')[0].prop("checked", result);
}
});
return false;
});
</script>