return true not working in jQuery - javascript

I am little bit new to jQuery. I have jQuery code as follow :
function callfunction() {
var email = $("#email").val();
var passwrd = $("#password").val();
$.ajax({
url: "checklogin.php?email="+email+"&pass="+passwrd,
type: "post",
success: function (response) {
if(response == '1') {
alert('Login Successfull. Proceed to pay now');
$('#getre').show();
$('#signuplink').hide();
$('#password2').hide();
$('#login').hide();
$('#email').attr('disabled','disabled');
return true;
}
if(response == '0') {
alert('Login Failed !!! Try Again');
return false;
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
and its HTML code is as follow :
<form class='form form-inline' style="margin-top:20px;" method="post"
action="#">
<input type="text" name="email" id="email" class="amount form-control required" Placeholder="Enter Email ID" required="">
<input type="password" name="password" id="password" class="amount form-control required" Placeholder="Enter Password" required="">
<input type="submit" name="getr" class="mob-btn btn btn-primary btn-info-full" value="Login" onClick="return callfunction()">
</form>
When I am submitting the form and response ==0 then the form is submitting the data while I dont want to submit the data is response=0.
How I can achieve this ?

take out type="submit" from your submit button element. This will prevent the form from being submitted before the ajax request is fired off.
<input name="getr" class="mob-btn btn btn-primary
btn-info-full" value="Login" onClick="callfunction()">
then when you receive your ajax response you can call form.submit() like so:
$.ajax({
url: "checklogin.php?email="+email+"&pass="+passwrd,
type: "post",
success: function (response) {
if(response == '1')
{
$('.form-inline').submit();
alert('Login Successfull. Proceed to pay now');
$('#getre').show();
$('#signuplink').hide();
$('#password2').hide();
$('#login').hide();
$('#email').attr('disabled','disabled');
}
if(response == '0')
{
alert('Login Failed !!! Try Again');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Related

jQuery Ajax Email Validator

I have a simple form for a person to fill in their email address. My Ajax script is set to check this address with the database and validate if it exists or not. That step works but I'm stuck on getting the form to submit if the email doesn't exist.
This is my HTML
<form action="user_add.php" method="post" id="addform">
<input
type="text"
class="form-control"
name="email"
id="email"
required
value=""
/>
Check
</form>
This is my JS
function check() {
$.ajax({
url: 'checkusers.php',
data: {
email: $('#email').val()
},
type: 'POST',
dataType: 'json',
success: function (data) {
if (data == true) {
alert('Please note: A user with this email address already exists.')
return false
} else if (data == false) {
//return true; --- this doesn't work
//$('form').submit(); --- this doesn't work
$('form').trigger('submit') // --- this doesn't work
}
},
error: function (data) {
//error
}
})
}
What am I doing wrong here?
Using regular expressions is probably the best way.
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function check(){
var email = $('#email').val();
if (validateEmail(email)) {
$.ajax({
url: "checkusers.php",
data: {
'email' : email
},
type: "POST",
dataType: 'json',
success: function(data) {
if(data == true) {
alert('Please note: A user with this email address already exists.');
return false;
}
else if(data == false) {
//return true; --- this doesn't work
//$('form').submit(); --- this doesn't work
$('form').trigger('submit'); // --- this doesn't work
}
},
error: function(data){
//error
}
});
} else {
// error email not valid
}
}
Thank you to everyone for your input. I had a stray submit button higher up on the page I was working on
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-primary">
When I took this out, the following bit worked:
$('form').trigger('submit');

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

Mailchimp via jQuery Ajax. Submits correctly but JSON response is returned as a separate page

I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>

How to trigger javascript on node events?

I have a standard login page. When the database validates the credentials entered by the user I want to make changes to the page, example: create element saying "Login Successful", using a static javascript file. How do I communicate to a static javascript file that the login was successful thus triggering the changes? I'm using Parse right now for my database.
html:
<form class="form" method="post">
<div>
<label>Username:</label>
<input class="form-control" id="username" type="text" name="username">
</div>
<div>
<label>Password:</label>
<input class="form-control" id="password" type="password" name="password">
</div>
<input class="btn btn-custom" type="submit" id="loginSubmit" name="loginSubmit" value="Submit">
</form>
Node with Express and Parse:
login.post('/login', function (req, res) {
Parse.User.logIn(req.body.username, req.body.password, {
success: function(user) {
console.log("Login Successful!");
res.redirect('/');
},
error: function(user, error) {
res.redirect('/login');
console.log("Login Unsuccessful! " + error.message);
}
});
});
The solution was using jQuery's Ajax method.
$('#loginSubmit').on('click', function () {
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
if (xhr.status === 200) {
console.log("fun time?");
$('body').css("background-color", "yellow");
}
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
});

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources