How to save var value outside ajax success function? - javascript

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!

You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.

I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Related

e.PreventDefault and ajx submit not working together [return true] is not working

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;
}
}
});
});

Unable to prevent form when a condition is met

I am working on a form I wish to validate via jQuery $.ajax. The form should only be submitted if a certain condition, data == 1
var preventSubmit = function() {
return false;
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
return true;
}
}
});
};
$("#comment_form").on('submit', preventSubmit);
The submit happens regardless if the condition is met or not.
Where is my mistake?
If I use e.preventDefault();, how can I "undo" it in case if data is equal to 1?
You won't be able to allow the submission of the form with a return value of true because the ajax is happening asynchronously (by the time it completes the function has already finished executing). What you can do is always prevent the form from submitting in the preventSubmit function, then submit it programmatically.
var preventSubmit = function() {
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
form.off();//remove bound events (this function)
form.submit();//manually submit the form
}
}
});
return false;//the return needs to be at the end of the function and will always prevent submission
};
$("#comment_form").on('submit', preventSubmit);
Anything after the return false; will never be executed.
Also, you should be doing form validation on the front-end rather than the back-end. With that being said, you should not remove the validation from the back-end.
One more thing, try doing HTML5 form validation first as that's your first line of defence.
You're looking at something on the lines of:
var validateForm = function(e) {
// prevent the default form action to allow this code to run
e.preventDefault();
var isValid = false,
form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
// Validation goes here
// ...
// isValid = true;
if (isValid) {
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// do something with the response. Maybe show a message?
form.submit();
}
});
}
};

$.ajax json GET reverts all jquery after page load

So I have a one page site, that only shows a login with username and password.
I have the $.ajax fire on the submit click.
What I want is for it remove the login box and load in the page that will have all the content ready for the ajax content to go into.
$.ajax function works and was tested by alert(n); the number for my json array.
What happens is after the box disappears and the page loads, it reverts back to the login box.
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
});
});
This is a pretty common problem. When you bind to a submit event, you are effectively able to run some logic, but unless you stop it, the event will continue to propagate and will also run the normal submit logic, which causes a full page refresh. This is fairly easy to prevent:
$(document).ready(function() {
$('#launchform').on('click', function(e) {
e.preventDefault(); // Add this
});
});
As stated in another answer, you can also return false;. That is sometimes a better way to do it when using jQuery as it effectively cancels everything. Although, in non-jQuery solutions, it doesn't stop the event bubbling. You can read more details about why here: event.preventDefault() vs. return false
If you are performing this within a <form> element then the form is probably submitting after the ajax call and reloading the page. Try adding:
return false;
to the end of the click event function to prevent the form submitting.
So the above code would look like:
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
return false;
});

jQuery $.post not executing, how to fix

I am working on a Plugin for WordPress and am having issues with the js code below executing the $.post.
The js is called, form validation takes place, the form inputs are serialized into post data correctly, the $.post just doesn't execute.
The form is being posted from the Admin, currently I can't get the .submit action to work so am using .click to execute the js function. This may be related to the issue, I am not sure... The form will load without submitting if I use the .submit action, versus using the .click action... never had this issue before and it is pretty frustrating to say the least.
Here is the code:
jQuery(document).ready(function($) {
$("#edit_member_submit").click( function() {
// define
var numbers = /^[0-9]+$/;
var referrer_id = $("#referrer_id").val();
// Validate fields START
if( !referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
// Define a data object to send to our PHP
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
var data = $("#edit_member_form").serializeObject(); //the dynamic form elements.
//alert(JSON.stringify(data));
data.action = "edit_member_info"; //the action to call
data._ajax_nonce = custajaxobj.nonce; // This is the name of the nonce setup in the localize_script
// Define the URL for the AJAX to call
var url = custajaxobj.ajaxurl;
//alert( JSON.stringify( data ) );
//alert( JSON.stringify( url ) );
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
return false;
});
});
Seems like the last section is having issues:
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
$.post( "ajax/test.html", function( data ) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(data);
});

Form Validation with Jquery and AJAX

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
});

Categories

Resources