I have this scenario where when submiting html form we call javascript method to validate the form. Problem is that validation is done through Ajax request calling php function which returns json array which is empty or contains array with errors.
I am using Ajax request as this newValidation function will be used on all forms on my application so all field ids names and stuff is dynamic same as validation messages.
Console log results are:
Undifiend
It should be True or False.
So it looks like .done run after console.log.
I thought .done is waiting until ajax is finished and only then proceed?
Reason why I am asking I need this .done to run first so it can assing answer variable and only then return boolean to the form. Does this even possible?
UPDATED:
Html form:
<form id="systemManagementSettings" action="#" method="POST" onsubmit="return newValidation('systemManagementSettings')">
JavaScript
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
answer = true;
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
answer = false;
}
});
console.log(answer);
return answer;
}
How do you prevent the form from actually being submitted?
Use event.preventDefault().
UPDATE
Submit the form in the done function.
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
$.ajax({
url: $('#'+formId).attr('action'),
type: "POST",
data: {form: $('#'+formId).serializeArray()},
});
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
}
});
return false; //all the time
}
Related
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();
}
});
}
};
I want to pass data via AJAX. The variable consists of both numbers and non-alphanumeric variables ("001.0/210.00"). My $_POST['task'] doesn't return a value. I've attempted to change the data to JSON, but that doesn't seem to work.
$(document).ready(function(e){
var trigger = $('.task a'),
var container = $('#content1');
trigger.on('click', function(e){
var shotElement = event.currentTarget.children[0].innerText;
$.ajax({
type : 'POST',
url : 'indexPipeline.php',
data : { task: shotElement },
success : function(response) {
$("#displayPipeline").load("indexPipeline.php");
}
});
return false;
});
});
I have a global variable creditAmount that is populated via an ajax call when a user logs in. I would like to use that variable later on in another function that is called after login. How do I keep the value of creditAmount available for this later function?
This is wherecreditAmount gets defined and populated:
var creditAmount = "";
function getCustomer() {
$(function() {
$("#anId").submit(function(event){
event.preventDefault();
var form = this;
var custEmail = $("anotherId").val();
$.ajax({
url: "/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "json",
complete: function(data) {
creditAmount = data.responseJSON;
form.submit();
},
});
});
});
}
And then this is where I need to use creditAmount:
function getPendingCredit(){
var modal = $("#fresh-credit-iframe");
modal.load(function(){
$(this).contents().find("#fresh-credit-continue-shopping").click(function(data){
var enteredAmount = +($(modal).contents().find("#pending_credit_amount").val());
console.log(creditAmount);
$("#fresh-credit").hide();
});
});
}
Finally, this is how I call both functions, but by the time I get to here creditAmount is blank again
getCustomer();
if(creditAmount != ""){
showModal(closeModal);
getPendingCredit(creditAmount);
}
set a delay or use promises/callback. There is a little time gap between the request which is sent with ajax and the response that is received to populate the variable.
I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.
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);
});