Paul here. I'm working on a simple form with one checkbox, a textarea and some inputs. I got POST to database to work on my localhost, I can submit all form data successfully, but having trouble when a checkbox in my form is unchecked: feedback fails, it says 'please wait' and just spins. The database registers the data okay in either case, but I would appreciate any help to get it more responsive.
The main problem occurs when user leaves 'subscribe' unchecked: no feedback.
I'm also hoping to learn how to create deeper feedback, such as "Your message has been sent. We'll be in touch shortly. You have also been added to our mailing list."
Here is my php:
<?php
/*Contact Form*/
//ajax call
if(isset($_GET['action'])&& $_GET['action'] == 'contact'){
mysql_connect('localhost','******','**********');
mysql_select_db('*******');
//sanitize data
$email = mysql_real_escape_string($_POST['contact-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = 'error';
$message = 'You did not enter an email address!';
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingContact = mysql_query("SELECT * FROM contact WHERE contact_email_address='$email'");
if(mysql_num_rows($existingContact) < 1){
//database insert code
$message = $_POST['contact-textarea'];
$checkbox = $_POST['contact-checkbox'];
$name = $_POST['contact-name'];
$date = date('Y-m-d');
$time = date('H:i:s');
$insertContact = mysql_query("INSERT INTO contact (contact_email_address, contact_date, contact_time, contact_name, contact_message, contact_checkbox) VALUES ('$email','$date','$time','$name','$message','$checkbox')");
if($insertContact){
$status = 'success';
$message = 'your message has been received';
}
else {
$status = 'error';
$message = "Oops, there's been a technical error!";
}
}
else {
$status = 'error';
$message = 'This email address has already been registered!';
}
}
//return the JSON response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
and here is my html:
<form id="contact-form" action="?action=contact" method="post">
<legend>Contact us:</legend>
<label for="email">Your email: *</label>
<input type="email" name="contact-email" id="contact-email" placeholder="Your email here..." required></input>
<label for="name">Your Name: *</label>
<input type="name" name="contact-name" id="contact-name" placeholder="Your name here..." required></input>
<label for="message">Your Message: *</label>
<textarea id="contact-textarea" name="contact-textarea" placeholder="Type your message here..." rows = "8" cols = "35" required></textarea>
<label for="checkbox">Subscribe to Newsletter?</label>
<input type="checkbox" name="contact-checkbox" id="contact-checkbox" value="1"></input>
<p id="contact-response"></p>
<input type="submit" name="contact-button" id="contact-button"></input>
</form>
and here's the javascript:
$(document).ready(function(){
$('#contact-form').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#contact-response');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formsstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
})
My best guess is that it has to do with the fact that jQuery.serialize does not serialize the checkbox if it is unchecked.
Compare:
Checked: contact-email=test%40gmail.com&contact-name=test&contact-textarea=test&contact-checkbox=1
Unchecked: contact-email=test%40gmail.com&contact-name=test&contact-textarea=test
As a result, $_POST['contact-checkbox'] returns null which probably changes the data that's being returned to include a PHP warning, which breaks the JSON you're returning. To fix it, try this (I'm not fully sure it'll work):
if ( isset($_POST['contact-checkbox']) ) {
$checkbox = $_POST['contact-checkbox'];
}
else {
$checkbox = 0;
}
This checks if the contact checkbox is being posted. If so, if sets the checkbox value to the POST value. If not, the checkbox's set to 0.
Related
I can't update my database table on form submit with ajax. I don't know the reason or why this is happening. I posted my code below. Thanks.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$ime = !empty($_POST['ime']) ? stripslashes(trim($_POST['ime'])) : '';
$email = !empty($_POST['email']) ? stripslashes(trim($_POST['email'])) : '';
$poruka = !empty($_POST['poruka']) ? stripslashes(trim($_POST['poruka'])) : '';
$ime = htmlspecialchars($_POST['ime']);
$email = htmlspecialchars($_POST['email']);
$poruka = htmlspecialchars($_POST['poruka']);
//Validate Phone
if (empty($_POST["ime"])) {
http_response_code(400);
echo "Molimo, unesite Vaše ime i prezime.";
exit;
}else {
if (!preg_match('/^[a-zA-Z\s]+$/',$ime)) {
http_response_code(400);
echo "Dozvoljena su samo slova i space.";
exit;
}
}
//Validate Email
if (empty($_POST["email"])) {
http_response_code(400);
echo "Molimo, unesite Vaš e-mejl.";
exit;
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Nepravilan e-mejl format";
exit;
}
}
if (empty($_POST["poruka"])) {
http_response_code(400);
echo "Molimo, unesite Vašu poruku.";
exit;
}
if(isset($_POST['submit']) && !empty($_POST['ime']) && !empty($_POST['email']) && !empty($_POST['poruka'])){
$link = new mysqli("localhost", "admin", "", "proba");
$stmt = $link->prepare("INSERT INTO message(ime, email, poruka) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $ime, $email, $poruka);
$stmt->execute();
$stmt->close();
$link->close();
$email_message .= "Ime i prezime: ".htmlspecialchars($ime)."\n";
$email_message .= "E-mejl: ".htmlspecialchars($email)."\n";
$email_message .= "Poruka: ".htmlspecialchars($poruka)."\n";
$to = "somemail#mail.com";
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $email_message, $headers)) {
http_response_code(200);
echo "Poruka je uspešno poslata!";
exit;
} else {
http_response_code(400);
echo "Message is not successfully sent";
exit;
}} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
exit;
}
}
?>
Html
<div class="container">
<h1>Kontakt</h1>
<div id="form-messages"></div>
<form action="mail.php" method="POST" id="form">
<input id="ime" type="text" name="ime" value="<?php echo !empty($ime) ? $ime : ''; ?>" placeholder="Ime i Prezime">
<input id="email" type="text" name="email" value="<?php echo !empty($email) ? $email : ''; ?>" maxlength="20" placeholder="E-mejl">
<textarea name="poruka" id="poruka" placeholder="Poruka" maxlength="700" cols="30" rows="10"><?php echo !empty($poruka)?$poruka:''; ?></textarea>
<input id="submit" type="submit" name="submit" value="Pošalji Poštu">
</form>
</div>
and JQuery
$(function() {
// Get the form.
var form = $('#form');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: 'mail.php',
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#ime').val('');
$('#email').val('');
$('#poruka').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
If anybody has a solution, please do tell. I copied and pasted this amount of code for you to see the context. I don't know where to look for the solution. Thank you.
The reason this does not work via ajax (but does via a conventional postback) is that jQuery's .serialize() method does not serialise button values.
Therefore despite you having name="submit" on your button, its value will not be sent to the server in the request when you make the ajax call. In a conventional postback, it would be, if the button was used as the means to submit the form.
The documentation says:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button.
Although your button click may have triggered the code which submitted the form, it is no longer doing the form submission directly (instead ajax is doing it). In theory this could be triggered by anything, and jQuery has no way of knowing it was the button which started the process.
See https://api.jquery.com/serialize/ for more detail.
This causes you a problem because you test for the presence of this "submit" value before you make your database call and send your email. It's not really necessary to do this, since you're validating all the other input fields. I think you can just remove isset($_POST['submit']) from your if statement and you will have no problems. Therefore you'll be left with:
if(!empty($_POST['ime']) && !empty($_POST['email']) && !empty($_POST['poruka'])) {
I will be on the point. But anyways, THANKS IN ADVACE.
So basically When I submit the form I made, it submits and stuff, but it redirects the page to the PHP file, and shows this on the browser (not as an alert) :
{"status":"success","message":"Yer message was sent."}
when the data is successfully validated, and shows this
{"status":"fail","message":"Invalid name provided."}
when the form doesn't validate. What I want, is that when the form submits, it stays on the same page and if status is true or false, it should alert the message in the array.
I'll write down the scripts and the file names are: index.html, script.js and post.php
INDEX.HTML
<form action='post.php' id='post_message' name='post_message' method="post">
<p>
<input id='email' type="email" class='post' placeholder="Email goes in here.(Required) " class="width" name="email">
<br>
<input id='fname' type="text" class='post' placeholder="First Name (Required) " name="FirstName"><br>
<input id='lname' type="text" class='post' placeholder="Last Name (Required) " name="LastName"><br>
<input id='website' type="url" class='post' placeholder="Website? (Optional!)" class="width" name="website"><br>
<textarea id='message_text' placeholder="Your Message goes here. (Required, DUH!) " name='message'></textarea>
</p>
<button type="submit" class="submit" id='btnPost'></button>
<input type="hidden" name="action" value="post_message" id="action">
</form>
SCRIPT.JS
function clearInputs(){
$("#fname").val('');
$("#lname").val('');
$("#email").val('');
$("#website").val('');
$("#message_text").val('');
}
$('#btnPost').click(function() {
var data = $("#post_message").children().serializeArray();
$.post($("#post_message").attr('action'), data, function(json){
if (json.status == "fail") {
alert(json.message);
}
if (json.status == "success") {
alert(json.message);
clearInputs();
}
}, "json");
});
POST.PHP
<?php
if($_POST){
if ($_POST['action'] == 'post_message') {
$fname = htmlspecialchars($_POST['FirstName']);
$lname = htmlspecialchars($_POST['LastName']);
$email = htmlspecialchars($_POST['email']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
$date = date('F j, Y, g:i a');
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($message) ) {
fail('Please select a message.');
}
if( empty($email)) {
fail('Please enter an email');
}
$query = "INSERT INTO portmessage SET first_name='$fname', last_name='$lname', email = '$email', website = '$website', message = '$message', date = '$date'";
$result = db_connection($query);
if ($result) {
$msg = "Yer message was sent.";
success($msg);
} else {
fail('Message failed, Please try again.');
}
exit;
}
}
function db_connection($query) {
mysql_connect('127.0.0.1', '######', '####')
OR die(fail('Could not connect to database.'));
mysql_select_db('####');
return mysql_query($query);
}
function fail($message) {
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
And yes, it DOES submit the form to the database, but I can't overcome the alert and redirecting problem.
Thanks, again!
You can validate your form client side(using javascript)
HTML
<form action='post.php' id='post_message' name='post_message' method="post" onsubmit="return validate_form();">
Javascript
function validate_form()
{
var success = true;
if($("[name=FirstName]").val() == "")
{
success = false;
}
// your test case goes here
// you can alert here if you find any error
return success;
}
I got problem with shown validation error on below script, for example what I tested, I enter a correct email and wrong password, the request will returned both Wrong email address and Wrong password under each input textbox, it is not only Wrong Password is expected to shown, I tried hardcode required data in request.php and run this script directly, for either giving wrong data in in $_POST, the console response {"error":{"lemail":"Wrong email address","lpassword":"Wrong password"}}, can someone please have a look in my code what's goes wrong?
form with AJAX call:
<body>
<form role="form" method="post" id="login_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="lemail" name="lemail" placeholder="Your email"><span class="error" id="lemail_error"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="lpassword" name="lpassword" placeholder="Password"><span class="error" id="lpassword_error"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btn_login" data-loading-text="Loading...">Sign In</button>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btn_login').click(function(){
var parameters = $('#login_form').serialize();
$.ajax({
url: 'inc/callback/request.php',
type: 'POST',
data: {'parameters' : parameters},
dataType: 'json',
success: function(response){
if(response.success == 'logged'){
$('#login_form')[0].reset();
alert(response.success);
}else if(response.inactivate == 'inactive'){
alert('Your account is inactive!');
}else{
$('[id$="_error"]').html(''); //clear valid error msg
// display invalid error msg
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
});
});
});
</body>
request.php
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));
$func = new Functions();
$message = array();
//validate user's email and password from database
$check = $mysqli->query("SELECT * FROM `users` WHERE user_email='".$email."' AND user_password='".sha1(sha1($password))."'") or die($mysqli->error);
$rows = $check->fetch_array(MYSQLI_BOTH);
$num = $check->num_rows;
$uId = $rows['user_id'];
$uEmail = $rows['user_email'];
$uPwd = $rows['user_password'];
$uType = $rows['account_type'];
$uStatus = $rows['account_status'];
// validate user's account
if(empty($email) || $email !== $uEmail){
$message['error']['lemail'] = 'Wrong email address';
}
if(empty($password) || sha1(sha1($password)) !== $uPwd){
$message['error']['lpassword'] = 'Wrong password';
}
if(!isset($message['error'])){
if($uStatus == 0){
$message['inactivate'] = 'inactive';
}else{
$message['success'] = 'logged';
}
}
echo json_encode($message);
Edited:
Solved! nothing went wrong, just out of logic on variables comparison!! ;P
in you php code first you have to deserliazed ur code.. put these lines at top..
$searcharray = array();
parse_str($_POST[parameters], $searcharray);
$email = $mysqli->real_escape_string(strtolower(trim($searcharray['lemail'])));
$password = $mysqli->real_escape_string(trim($searcharray['lpassword']));
You are posting string not array, you need to use parse_str function first.
Remove this enctype="multipart/form-data" from form
<form role="form" method="post" id="login_form">
Replace your data: line with this
data: {'parameters' : parameters},
After add this to your PHP
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));
I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!
Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});
Console is not showing any errors, neither is Firebug so I'm at a loss as to why this isn't working.
My form:
<form action="" method="post" id="sendEmail">
<div class="alignleft">
<p><label for="order_ref">Photo ID:</label><input type="text" name="order_ref" id="order_ref" class="text smallinput" disabled="disabled" value="<? echo $ref; ?>"/></p>
<p><label for="order_name">Full Name:</label><input type="text" name="order_name" id="order_name" class="text" tabindex="10" /></p>
<p><label for="order_telephone">Contact Number:</label><input type="text" name="order_telephone" id="order_telephone" class="text" tabindex="20" /></p>
<p><label for="order_email">Email Address:</label><input type="text" name="order_email" id="order_email" class="text" tabindex="30" /></p>
</div>
<div class="alignright">
<p class="higher"><label for="order_message">Message</label><textarea name="order_message" id="order_message" class="uniform" tabindex="40"></textarea></p>
</div>
<div class="rounded color_grey"><p>Clicking confirm will mail your order to us. We'll be in touch shortly. <input type="submit" id="submit" name="submit" value="" class="alignright" /></p></div>
</form>
Then my JS:
// JavaScript Document
var g = jQuery.noConflict();
g(document).ready( function() {
g("#submit").click(function(){
// set initial error value to false
var hasError = false;
// set var for each form field
var order_ref = g("#order_ref").val();
var order_name = g("#order_name").val();
var order_telephone = g("#order_telephone").val();
var order_email = g("#order_email").val();
var order_message = g("#order_message").val();
// validate each of them
if(order_ref == '') { g("#order_ref").addClass('haserror'); hasError = true; }
if(order_name == '') { g("#order_name").addClass('haserror'); hasError = true; }
if(order_telephone == '') { g("#order_telephone").addClass('haserror'); hasError = true; }
if(order_email == '') { g("#order_email").val().addClass('haserror'); hasError = true; }
if(order_message == '') { g("#order_message").val().addClass('haserror'); hasError = true; }
// if there's no errors, proceed
if(hasError == false) {
//alert('no errors');
g.post("/photo/theme/foodphoto/includes/mail_send.php",
{
// pass each of the form values to the PHP file for processing
order_ref: order_ref,
order_name: order_name,
order_telephone: order_telephone,
order_email: order_email,
order_message: order_message
},
function(data){
// no errors? great now do what you want to show the user his message is sent
alert('sent');
}
);
}
return false;
});
});
And the PHP that should send it (mail_send.php)
<?php
// receive & save each of the vars from the AJAX request
$order_ref = $_POST['order_ref'];
$order_name = $_POST['order_name'];
$order_telephone = $_POST['order_telephone'];
$order_email = $_POST['order_email'];
$order_message = $_POST['order_message'];
// setup the email requirements
$to = "email#address.com";
$subject = "Order Has Been Placed";
// what must be in the mail message
$message = "The following order has been placed on your website:";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$order_name.' <'.$order_email.'>';
mail($to, $subject, $message, $headers);
?>
Console reports no PHP issues and Firebug (I am new at using this, so I might have skipped something?) reports no issues...?
What am I doing wrong?
Don't use the .click handler when using an input type of submit. Switch it to
g("#sendEmail").submit(function(){
Then see if when you click submit you invoke the JS as expected.
On a side note, you can reduce the amount of code that you write by serializing your form data with $(FORM ID or CLASS).serialize()
Cheers!
your js code is not called because you added submit button, when hit on that it will submit the form without waiting for a click event to be fired so either you change the button to click and then submit the form from click event or you can use submit an event
Cheers!