I'm trying to create a jquery contact form that sends an ajax request when clicked.
You can view it by visiting: http://childrensplaza.mn, and clicking the "click here to contact us button"
When testing this out though, After I click "send inquiry", it takes a while for the success message to show up, and I'm able to click it multiple times, causing my message to be sent multiple times.
The code for it is below ->
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
// Get the data from the form. Check that everything is completed.
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
How would I make it so that the success message shows up on the first click, and I am not able to send the same request multiple times?
This is easy enough to handle by adding a class when submitted the first time, and checking if the class is applied to determine whether or not to process the form. If the button already has the class, do not continue to process.
if ( $(this).hasClass("pressed") ) return false;
$(this).addClass("pressed");
Embedded in your code:
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
// Get the data from the form. Check that everything is completed.
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
if ( $(this).hasClass("pressed") ) return false;
$(this).addClass("pressed");
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
You could take one step further by resetting the class after successful ajax response.
$('#success').fadeIn(500); $("#submit").removeClass("pressed");
you can create a flag and control it with the ajax events beforeSend and complete ...
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
beforeSend: function(xhr, opts){
if($('#submit').hasClass("posting"))
xhr.abort();
else
$('#submit').addClass("posting");
},
complete: function(){
$('#submit').removeClass("posting");
},
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
Related
I am using ajax for my operations Create and Update
I can already create and update, but if I press or hit Enter key then this shows from another page which is kinda not look good to see, and it suddenly also create blank data after hitting Enter key.
{"success":false,"type":"update"}
For visual representation, here it what it looks like after hitting the Enter key on input fields
this is what my input is in my View
<input type="text" name="group[]" id="group" placeholder="Enter your Choice" class="form-control" />
in my Controller
public function addGroup(){
$result = $this->group_model->addGroup();
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function updateGroup(){
$result = $this->group_model->updateGroup();
$msg['success'] = false;
$msg['type'] = 'update';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
And in Model
public function updateGroup(){
$id = $this->input->post('txtId');
$field = array(
'group_name'=>$this->input->post('group')
);
$this->db->where('id', $id);
$this->db->update('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function addGroup(){
$field = array(
'group_name'=>$this->input->post('group'),
);
$this->db->insert('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
$('#myForm').submit(function(e){
$('#btnSave').attr('disabled',true); //disable the button
//.Your other code
success: function(response){
if(response.success){
$('#btnSave').attr('disabled',false); //enable the button
}
}
}
On CLicking the button disable the click event of submnit button which is default behaviour if you press Entern and enable it back if u get successfuly response.
In addition if you just want to disable enter key then u cn do it like this:
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
Change
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
into
$('#myForm').submit(function(e){
e.preventDefault();
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
beforeSend: function(){
$('#btnSave').attr('disabled',true);
},
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
$('#btnSave').attr('disabled',false);
return false;
});
});
Change button into Submit
Hope this Helps !!
I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});
I added a pop up form for email subscription and it is sending twice on submission and the confirmation message is also being displayed twice
Here is the code:
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function(e) {
e.preventDefault();
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! You have signed up for a trial. A member of our team wil soon be in contact :)</strong></p>");
setTimeout("$.fancybox.close()", 1700);
});
}
}
});
}
});
});
I don't think there's any need to write this line:
$("#contact").submit(function() { return false; }); // Remove this
You can remove this line:
$("#send").on("click", function(){ // Remove this
And write this instead:
$("#contact").submit(function(e) { // Add this
e.preventDefault(); // Add this
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
/* Other code */
});
I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});
I have a form with JS functions for checking empty fields and submit form without refreshing all page, I'm looking for a way to integrate email check function into what I'm having now:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#EBEBEB"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#EBEBEB"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#EBEBEB"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
}
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("textarea#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("textarea#phone").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Email sent</h2>")
.hide()
.fadeIn(1000, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Thanks for help.
To check an email, you can use:
var emailReg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
function isEmail(email) {
return emailReg.test(email);
}
//call isEmail wherever you need it
If I may comment further on your code, I would recommend you cache your selectors and reuse them:
var input = $('input.text-input');
input.css({backgroundColor:"#EBEBEB"}).focus(function() //... and so on
Also, if your DOM is correctly structured, you do not have to call your ids with input selectors, it just slows down your implementation because its iterating over every input in the DOM than just getting it directly. That means:
$("label#phone_error") // don't do this
$("#phone_error") // do this
Also, you can use a data object to pass to jquery, so rather than
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
Do this:
$.ajax(yoururl, {data:
{
name: name,
email: email,
phone: phone
}, // and so on