I’m trying to create a set of checkboxes that I can check and send over ajax.
What I’m looking to do ideally is to send several pieces of information via ajax to a php script, the checkbox that has been checked and also an id
The id is based on the URL, so I can get that using a $_GET['id'].
So if the user checked both boxes, the values that need to be sent to the php script will be:
53
57
1 – where this value is a value in the URL.
I have the following so far:
<input type="checkbox" name="test[]" value="53" id="part_shipping" />
<input type="checkbox" name="test[]" value="57" id="part_shipping" />
<input name="confirm" type="button" value="confirm" />
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$('input[type=button]').click( function() {
$(":checked").each(function() {
var value = $(this).val();
id = 'id:1';
data = 'shipping:' + value;
console.log(data);
});
$.post("ajax.php", data);
});
</script>
How do I append the id within the data so it reads:
shipping:53
shipping:57
id:1
If the
<input>tags are not already inside a<form>, then add one:Now, you can use jQuery’s
.serialize()to compose a data string of the format “name1=value1&name2=value2&name3=value3” etc., where the names are as given in the HTML :Checkboxes will only appear in the serialized form if they are checked. And I think I’m right in saying that the button won’t be included in the serialization.
The advantage of doing it this way is that the script is responsive to design changes in the form. If you add or remove a field, the javascript does not need to be changed.