I want to send an email to a user after they've filled out their details on a form. I want to validate the form (and if the form is valid) then send the email.
My validation for the form is in a separate JavaScript file and the code that I use to send the email is in my code-behind page. How would I be able to call the code-behind page method after the form has been validated?
Code Behind that I use to send the email(.cs) :
[WebMethod]
[ScriptMethod]
public static void sendMail(string fname, string lname, string email, string phone)
{
//some code here
}
External JavaScript file used for validation(.js):
function validateForm() {
/* some more code here */
}
HTML that contains the form:
<form id="franform" action="AnyPage.aspx" method="post">
<asp:Panel style="width: 60%; margin:auto; top:0px;" runat="server">
<!-- All components are added here -->
<button type="submit" id="send" class="send" onclick="javascript: return validateForm()">Submit</button>
</asp:Panel>
</form>
This is very similar to a question from yesterday.
Basically you need to change your button to an ASP button, reference your javascript function in onClientClick attribute and your button click event in code behind on onClick attribute e.g.
<asp:Button ID="send" runat="server" OnClientClick="return validateForm();" OnClick="send_Click" Text="Submit"/>
Your send_Click event could then call the sendMail method. Your javascript function needs to return true or false so that it only calls the on click event if true is returned.