I’m having some trouble using jQuery’s plugin Facebox to process some data from a form.
What I’m trying to accomplish is basically get the values of the number of selected checkboxes into an array and have it available in my popup to process it with PHP.
I have something like this on a form page:
form.html
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="button" name="replace" onClick="replace_equip()" />
There are more checkboxes, but I think these are enough to get started.
Here is replace_equip()
function replace_equip() {
var nArr = new Array();
$("input:checkbox[name=equip]:checked").each(function() {
nArr.push($(this).val());
$.facebox(function() {
$.ajax({
data: { name : nArr },
error: function() {
$.facebox("err");
},
success: function(data) {
$.facebox(data);
},
type: "post",
url: "test.php"
});
});
});
}
I’m trying to save the selected checkboxes into an array, in a way that I can use it for PHP processing in test.php.
I’m just getting started with jquery and javascript in general, so forgive any monster mistakes you may find!
To get started, there are a few stylistic issues with your code. First, you should opt not to use
newsyntax with Arrays, Objects, etc. Instead, declare yourArraywith something likevar array = [];. Second, you’re using an inlineonClick, which should be avoided if you’re using jQuery already. Instead, use something like$('input[name="replace"]').on('click', function() {...});. You should also consider usingcamelCasewith your functions, and if you like underscores, use them withvars.Now onto the meat of your question. I refactored your code like so:
In your PHP code, you would
json_decode()this array and work with it how you want. I also moved thetypeandurlparams to the top, as yourerrorandsuccessfunctions may get quite lengthy.I would consider reading JavaScript Patterns (at least the Essentials chapter).