I have some question. I have the html form with one hidden input element. And I have an array in my javascript code. I want to catch pressing submit button event (by using jquery) and push the array data in the hidden input.
The question is – what happens first: form date will flow to .php script or javascript’s array will be pushed into hidden input and afterwords .php script will be called? And why it is so?
TIA!
upd (code sample):
...
// process $_POST['domains']
...
<form action="registration?id=reg" method="post" enctype="multipart/form-data" id="reg_form">
...
<input type="hidden" id="domains" name="domains[]" value=""/>
...
<input type="submit" name="go" value="Register"/>
</form>
<script type="text/javascript">
var domainlist = [];
Array.prototype.indexOf = function (name) {
var ind = -1;
for (var i = 0; i < this.length; i++) {
if (this[i].name == name) {
ind = i;
break;
}
}
return ind;
}
$(document).ready(function() {
...
});
function checkDomain() {
...
req = $.ajax({
type: 'post',
cache: false,
url: 'ajax.php',
data: ...,
success: function(data) {
$('#domain_list_wrap').delegate('input:checkbox', 'click', function () {
var dmnName = $(this).attr('name');
domainlist.push({name: dmnName, cost: domainsArr[dmnName.split('.')[1]]});
...
});
$('#domain_cart').delegate('input:checkbox', 'click', function () {
domainlist.splice(domainlist.indexOf($(this).attr('name')), 1);
...
});
}
});
...
}
</script>
The JavaScript
submitevent is fired when the form is submitted, but before the request is made to the server (as JavaScript runs on the client side this makes perfect sense). Therefore, the way you have imagined it working should be fine, and you can bind to the form submit event using jQuery as follows:The
submitevent handler can also be used to cancel form submission (for example, if some validation fails) by returning false. It wouldn’t really work if the data was sent to the server first!