Can we run a js function on a submit button and php on the same button. I have a submit button that sends form data to a database using php, but I want a second action (JavaScript function) to take place once the button is clicked as well. Is that possible?
2
-
1What have you tried already before asking the question?Sunil– Sunil2017-12-12 03:08:20 +00:00Commented Dec 12, 2017 at 3:08
-
Possible duplicate of Form Submit Execute JavaScript Best Practice?Derek Brown– Derek Brown2017-12-12 04:05:44 +00:00Commented Dec 12, 2017 at 4:05
Add a comment
|
3 Answers
The correct method is to call the javascript function on the onsubmit attribute in the form with a return state. Thus the form will wait until the JavaScript returns true before proceeding with submit.
The HTML
<form action="something.php" onsubmit="return someJsFunction()">
<!-- form elements -->
<input type="submit" value="submit">
</form>
The JavaScript
function someJsFunction(){
//your validations or code
if(condition == false){
return false; // This will prevent the Form from submitting and lets
// you show error message or do some actions
}else{
return true; // this will submit the form and handle the control to php.
}
}
Comments
You can do this with the jQuery submit callback for this
$("form").submit(function(){
alert("Submitted");
});