I need to take some actions which involve updating a database table when a user clicks on the form submit button. I want this action to complete before I now submit the form but it doesn’t work yet. Here is the codes
// On form submission
$("#profile").submit(function() {
submitForm(function(result) {
return result;
});
});
function submitForm(callback) {
var dept;
if (IsEmpty($("input[name=dept_id1]").val())) {
dept = $("select[name=dept_id]").val();
$.post("funcs.php", {'dept':dept, op:'select'}, function(d) {
callback(true);
});
} else {
dept = $("input[name=dept_id1]").val();
$.post("funcs.php", {'dept':dept}, function(d) {
callback(true);
});
}
}
If I prevent the form from submitting, the action will complete successfully but I’ll have to manually go to the result page to see the changes. If I allow the form to submit, the changes won’t take effect.
The codes I pasted here allows the form to submit after the ajax function, but it doesn’t make any changes on the server side.
Thanks for any help.
I’d recommend using a button rather than submit button in your form in this situation. If you’re currently using, for example:
Then consider instead doing:
This would prevent the form from automatically submitting when you click the button. You could actually submit the form in the callback function, for example:
Or something along those lines. Code not tested, but it should be something along these lines.
Edit: After doing that, you’d want to drop the eventhandler in your original code for $(‘#profile’).submit …otherwise you’d be running that ajax stuff twice.