As from the title, I want to submit a form by click a span element. I also want to prevent the page from refreshing. I also want to add normal submit button for mobile view. But on submit won't work unless I directly submit the form. Is there a way to submit the form with ajax when I hit the span element? I also know that having submit elemnt in form might give trouble to sending data to php. So, is there a way to resolve this? My code -
HTML
<div >
<div >
<form action="" id="contactForm">
<label for="name" >Your Name</label>
<input type="text" name="name" id="name" required><br>
<label for="email" >Email</label>
<input type="email" name="email" id="email" required><br>
<label for="subject">Subject</label>
<textarea name="subject" id="subject" required></textarea>
<input type="submit" id="send" value="Send">
</form>
</div>
<div >
<div >
<img src="photos/cloud.png" alt="cloud" width="700px">
<span id="paper">
<i ></i>
</span>
</div>
</div>
</div>
Jquery
$("#paper").on("click", function () {
$("#contactForm").validate();
console.log("good")
$("#contactForm").on("submit", function (e) {
e.preventDefault();
var dataString = $(this).serialize();
console.log("nice")
$.ajax({
type: "POST",
url: "_actions/sendmail.php",
data: dataString,
success: function () {
console.log("best")
$("#paper").addClass("posRun");
}
});
return false;
});
});
CodePudding user response:
Never add additional events inside other event callback!
You should just trigger form submunition on click, not add event:
$(document).on("click", "#paper", function () {
$("#contactForm").validate({
submitHandler: function(form) {
console.log("good");
form.submit();
}
});
});
$(document).on("submit", "#contactForm", function (e) {
e.preventDefault();
var dataString = $(this).serialize();
console.log("nice")
$.ajax({
type: "POST",
url: "_actions/sendmail.php",
data: dataString,
success: function () {
console.log("best")
$("#paper").addClass("posRun");
}
});
return false;
});