mrAnderson
mrAnderson

Reputation: 61

Run JavaScript and php on one button

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?

Upvotes: 0

Views: 2078

Answers (3)

Kartik Prasad
Kartik Prasad

Reputation: 740

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

Upvotes: -2

Clain Dsilva
Clain Dsilva

Reputation: 1651

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.
     }
   }

Upvotes: 1

Shalitha Suranga
Shalitha Suranga

Reputation: 1146

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>

Upvotes: 3

Related Questions