Function to impact a parent function - javascript

I have a function:
function validateForm() {
var result = ''
$.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if (data!=='') {
// make function validateForm return false
}
}
);
};
I would like to know if there is a way to do something in my condition that will apply to the function above the get request.
What I want to do exactly is that if my condition is met in my get request, then the function validateForm() return false.
Is there a way to accomplish that?
EDIT:
Here is what I tried
js:
var validateResult;
$('#but_id').click(function(event){
validateForm().done(function(){
if(!validateResult)
event.preventDefault();
});
})
function validateForm() {
var result = ''
return $.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if(data!==''){
validateResult = false;
}
}
);
};
html:
<form method="post" onsubmit="return validateForm();">
<input id='username' type="text" name="username"/>
<button type="submit" id='but_id'>Submit</button>
</form>

I assume you're trying to do something like this:
if (validateForm()) {
doSomething();
}
else {
displayError();
}
Instead, simply do this:
function validateForm(){
//...
$.get(
'/auth_validate_username/',
{ 'result': result },
success: function(data) {
doSomething();
},
error: function(data) {
displayError();
}
);
}
You just have to make sure that your server responds accordingly. I.e., your server shouldn't be generating a successful 200 response for every request to /auth_validate_username.
$.get is just a shorthand for $.ajax(). Read more about the callbacks in the docs.
Per your comment!
function doSomething(data, textStatus, jqXHR) {
$('form').submit();
}
function displayError(jqXHR, textStatus, errorThrown){ ... }
function validateForm(event){
$.ajax(
url: '/auth_validate_username/',
data: {"result": result},
success: doSomething,
error: displayError
);
return false; // prevent default form submit
}
$('form').submit(validateForm);
It would've been nice to know this was your goal from the start.

Use a sync call may implement what you want with 'async: false' when start a ajax call.
Tried in Chrome console and works.
function validateForm() {
var result = ''
var retval=true;
$.ajax(
'/auth_validate_username/',
{
async: false,
data: { 'result': result }
}
).done(function ( data ){
if(data !== ''){
retval = false;
}
});
return retval;
};

The ajax will complete after the function completes. So there is no way to do what you are looking for. Re-arrange your design or submit the form from the success function in the get.
Here is my crazy approach at a workaround
var validating = false;
var safeSubmit = false;
function validateForm()
{
validating = true;
$("#formElementId").ajaxStop(function () {
if( !validating ) return;
if( safeSubmit ) $(this).submit();
validating = false;
$(this).unbind("ajaxStop");
});
var result = ''
$.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if (data!=='') {
// make function validateForm return false
}else{
safeSubmit = true;
//this could also simply be
//$("#formElementId").submit();
}
}
);
return false;
}

Try using done with your function call.
In html
<input type ="button" id="yourButtonId" value="submit" />
In javascript
var validateResult;
$('#yourButtonId').click(function(event){
validateForm().done(function(){
//your code
if(!validateResult)
event.preventDefault();
});
})
function validateForm() {
var result = ''
return $.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if(data!==''){
// make function validateForm return false
validateResult = false;
}
}
);
};

Related

Javascript validation works...and fails

I have the following Javascript code in my web page that SHOULD ensure data validation and then (if the form is valid) submit the data to an AJAX call:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
}
});
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
The problem is, the validation works, but it doesn't. When the form fields are not valid, it hits this block:
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
and the alert is displayed. The very next line should force the function to exit, stopping execution of any remaining code, but for some reason it doesn't. Instead, the remainder of the code executes as if the form is valid, and the alert for the AJAX failure pops up.
Why does the 'return false' not actually force the function to exit, and what am I missing here?
return false is a statement of the anonymous function function (form) {... which is called for each form element. The anonymous function function (event) {... doesn't have a return statement. The filter function in Array.prototype.filter.call(forms, has to return either true or false for each element to work as expected, not false or undefined. You could use e.g. Array.prototype.every and/or Array.prototype.map instead of Array.prototype.filter:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.map.call(forms, function (form) {
if (!form.checkValidity()) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
return true;
}
});
if (!validation.every(el => el)) return false;
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>

How can I validate form using JS and after that with PHP and Ajax?

I have an HTML form which I am validating using JavaScript like below code. All the JavasCript code is in an app.js file.
App.js file
function validateForm () {
var amount = document.forms["salesform"]["amount"];
var buyer = document.forms["salesform"]["buyer"];
var buyerRegex = /^[a-zA-Z0-9_ ]*$/;
var receipt_id = document.forms["salesform"]["receipt_id"];
var receiptIdRegex = /^[a-zA-Z_ ]*$/;
let items = document.querySelectorAll(".items")
var itemsRegex = /^[a-zA-Z_ ]*$/;
var buyer_email = document.forms["salesform"]["buyer_email"];
var note = document.forms["salesform"]["note"];
var city = document.forms["salesform"]["city"];
var cityRegex = /^[a-zA-Z_ ]*$/;
var phone = document.forms["salesform"]["phone"];
var phoneRegex = /^[0-9]*$/;
var entry_by = document.forms["salesform"]["entry_by"];
var entryByRegex = /^[0-9]*$/;
function validateEmail(email) {
var 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());
}
if (amount.value == "") {
alert("Please enter the amount.");
amount.focus();
return false;
} else if (isNaN(amount.value)) {
alert("Amount must be only numeric value.");
amount.focus();
return false;
} else if (amount.length > 10 ) {
alert("Amount must be less than 10 characters long.");
amount.focus();
return false;
}
// more validation.....
return true;
}
In this file I have another jQuery Ajax code validate the form using Server. So that I have added following Ajax code blow that JS validation code:
$("#salesForm").submit(function(e) {
e.preventDefault();
$.ajax({
url : '../process/add-data.php',
type: 'POST',
dataType: "html",
data : $(this).serialize(),
beforeSend : function () {
$(".formResult").html("Please wait...");
},
success : function ( data ) {
$(".formResult").html( data );
}
});
});
for the HTML form
<form name="salesform" id="salesForm" onsubmit="return validateForm();" method="POST">
Now when the form is validating using JavaScript then it also vaidating the form using Ajax.
But first its should validate using JavaScript and then Ajax.
Remove onSubmit from the element and modify your Ajax function to return invalid form BEFORE making the call.
$("#salesForm").submit(function(e) {
e.preventDefault();
if(!validateForm()) return;
$.ajax({
url : '../process/add-data.php',
type: 'POST',
dataType: "html",
data : $(this).serialize(),
beforeSend : function () {
$(".formResult").html("Please wait...");
},
success : function ( data ) {
$(".formResult").html( data );
}
});
});
You need to return false inside beforeSend callback, as it is described in official jQuery documentation:
beforeSend Type: Function( jqXHR jqXHR, PlainObject settings )
A pre-request callback function that can be used to modify the jqXHR (in
jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to
set custom headers, etc. The jqXHR and settings objects are passed as
arguments. This is an Ajax Event. Returning false in the beforeSend
function will cancel the request. As of jQuery 1.5, the beforeSend
option will be called regardless of the type of request.
So, you need to do something like this:
beforeSend : function () {
$(".formResult").html("Please wait...");
if(!validateForm()) {
// Here you remove your "Please wait..." message
return false;
}
// Or simply return the value from validateForm():
// return validateForm();
},
And, of course, remove the onsubmit="return validateForm();" from your form tag.

Ajax call not working in function

I have one function in java script. I want to send my form in ajax call after validation. I wrote ajax code for this but it's neither working nor giving any error on console even .
What can i do ?
javascript
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$.ajax({
type: "POST",
url: "quoteProcess.php",
data : $('#testform').serialize(),
success: function(data) {
alert(data);
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}

jQuery .ready() function use in other event

Below is my .ready() function:
$(document).ready(function()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
This function will run when the page load, but I would like to use this function in other event like .click(). Do I need to rewrite the function?
Just create the function with a name, and use it everywhere! Example:
$(document).ready(function(){
function yourFunction(){
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
yourFunction();
$('#element').click(function(){
yourFunction();
});
});
name the function and call that function on your click event.
sample:
<button id='btn'> click me </button>
$(document).ready(function(){
foo();
$("#btn").click(function(){
foo();
});
function foo(){
alert('data');
}
});
JSFIDDLE DEMO
This function will run when the page load, but I would like to use
this function in other event like .click().
Try using array of functions as parameter to .ready() , name first function in array , set named function to property of this:document within first array ; named function should be available at second function within array as property of this:document
$(document).ready([
function fn() {
this.fn = fn;
console.log(this)
},
function() {
$("div").click(this.fn)
}
])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click</div>
First Create a function that will be called on your click event. Please see below example.
$(document).ready(function(){
$("#samplebutton").on("click",function(){
example();
});
function example(){
alert("clicked");
}
});

jQuery MVC - Basic jQuery if else statement which CANT work?

I got an if-else script:
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
if (isFav(fid)) {
alert("Do you want to remove from favorite?");
}
else {
alert("Add to favorite?");
}
});
calling the isFav script function:
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}
which in turn calling my controller action:
public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}
Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered.
I cant get what is wrong here. Any idea?? Please help..
The ajax request in isFav is async and the isFav method will return before it is completed.
This is probably how I would solve it:
function isFav(fid, callback) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { callback(result); }
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid,function(result){
if(result && result.toLowerCase() == "true"){
alert("Do you want to remove from favorite?");
} else {
alert("Add to favorite?");
}
});
});
You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed.
You're gonna need some remodeling.
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) {
if(result == 'favorite') alert("Do you want to remove from favorite?");
else alert("Add to favorite?");
}
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid);
});

Categories