Reputation: 11
I am using this current Ajax request to grab the ids of the "checked" checkbox I have.
$(function() {
$(":checkbox").click(function(){
$.post("ci_editor.php", { id: this.id, checked: this.checked });
});
});
This function works, the problem is I have no idea how to receive it in the "ci_editor.php" file.
I know I have to $_POST method, but what do I use as a parameter since I don't even know the id of what is going to be checked?
Upvotes: 0
Views: 139
Reputation: 5541
$_POST is not a method, it's a superglobal variable, so the value you send is contained within $_POST. $_POST can also contain several values as a associative array, in those cases you grab the value using a key such as $_POST['id'] which represents the array index associated to the 'id' key within $_POST.
There are several things not quite right in your logic, first of all, don't post the values on the click of the checkbox unless there is only one and you have no other better way to trigger the post. If there are several checkboxes you could have many, not just one, so your third line should be something like (notice the array):
$.post("ci_editor.php", [{ id: this.id, checked: this.checked }, { id: this.id2, checked: this.checked2 }] );
Then $_POST should be the array itself, you just need to traverse it and that would do the trick.
To handle a varying number of checkboxes, try something like this:
var payload = new Array();
$.each( $(":checkbox") , function( index, value ) {
//value holds the reference of the check box
if(value.attr('checked')){
//Build the object with whatever values from the checkbox you require.
payload.push( { id: value.id, checked: value.attr('checked') } )
}
})
and use payload array as your $.post payload.
Upvotes: 0
Reputation: 657
If the checkbox is not checked out, you won't be able to catch the post. In this case, you should create an array with all expecting inputs name (including the checkboxes) and loop through this array, checking if the input name exists on $_POST array.
In negative case, you are sure the user didn't click the checkbox.
Upvotes: 1