0

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

3 Answers 3

3

You can add onclick() event to submit button. it will execute before submitting the form.

var buttonClick = () => {
  alert("Do what you want to do!"); // Add your second work here
}
<form action="yourfile.php">
    <input type="submit" onclick="buttonClick();">
</form>

Sign up to request clarification or add additional context in comments.

Comments

1

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

-2

You can do this with the jQuery submit callback for this

$("form").submit(function(){
    alert("Submitted");
});

see. https://www.w3schools.com/jquery/event_submit.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.