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
});
Related
I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.
This my javascript Function:
$(document).ready(function () {
$("#signupform").submit(function (event) {
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
event.preventDefault();
//Form post data still sent?
}
}
});
}
else alert("Captcha not null");
});
});
You need to move event.preventDefault(); up so it comes before the ajax call.
Use $("#signupform").submit(); in an else block to programmatically submit the form.
$(document).ready(function () {
$("#signupform").submit(function (event) {
event.preventDefault();
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
//Form post data still sent?
} else {
$("#signupform").submit();
}
}
});
}
else alert("Captcha not null");
});
});
You would need have the form event.preventDefault(); before making the ajax request.
$("#signupform").submit(function (event) {
event.preventDefault();
When the ajax request is returned, you can submit the form using:
if (data != 0) {
$("#signupform").submit();
}
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;
}
}
});
});
<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.
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'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>