Javascript: return false from asynchronous function - javascript

I'm having some real trouble trying to get this form to work properly. The form should validate each field and successfully charge a credit card before submitting.
The issue is that I can't pass my return value to the parent function to prevent the form from submitting. I read this post and tried using deferred objects, a callback function, and placing return statements all over the place but I'm missing something. I've been at this for about a week and the frustration is getting to me. Could anyone help me with this? I would greatly appreciate it and thanks!
HTML:
<form onSubmit="return billingfunction1();" name="form5" method="post" action="" id="newform">
</form>
JS: (trimmed to size)
function billingfunction1() {
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var cardtype = $.trim($("#cardtype").val());
var maxlen = 16;
var digits = cardnumber.toString().length;
var submiteval;
if (cardtype == '') {
// alert("Enter Card Type");
$('#cardtype_msg').html('Enter Card Type.');
$('#cardtype').css('border','1px solid #28a616');
$('#cardtype').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else if (nameoncardfirst == '') {
//alert("Enter Name On Card");
$('#nameoncardfirst_msg').html('Enter First Name On Card.');
$('#nameoncardfirst').css('border','1px solid #28a616');
$('#nameoncardfirst').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else if (nameoncardlast == '') {
//alert("Enter Name On Card");
$('#nameoncardlast_msg').html('Enter Last Name On Card.');
$('#nameoncardlast').css('border','1px solid #28a616');
$('#nameoncardlast').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else {
function foo(callback) {
return $.ajax({
url: 'edit_billing2.php',
data: "nameoncardfirst=" + nameoncardfirst+ "&nameoncardlast=" + nameoncardlast + "&street_address2=" + street_address2 +"&city2=" + city2 +"&state=" + state +"&zip=" + zip + "&cardnumber=" + cardnumber + "&expirationdate=" + expirationdate + "&cvv=" + cvv + "&cardtype=" + cardtype+ "&amount=" + amount + "&gender=" + gender + "&first_name=" + first_name + "&last_name=" + last_name + "&address=" + address + "&address2=" + address2 + "&city=" + city + "&post_code=" + post_code + "&country=" + country + "&mobile=" + mobile + "&email=" + email + "&newsletter=" + newsletter + "&make=" + vehicle + "&model=" + model + "&model_year=" + model_year,
success: callback
});
}
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
//alert(response);
result = response.split('_');
//alert("Successfully Saved");
alert(result[0]);
if(result[0]=="Your Payment has completed successfully")
{
console.log("Payment Success");
submiteval = true;
}
else
{
console.log("Payment Failed, Aborting form submission.");
submiteval = false;
}
return submiteval;
}
console.log("Valid inputs: attempting to pass via AJAX");
foo(myCallback).done(function(response) {
return submiteval;
});
}
EDIT:
I tried using event.preventDefault() to stop the submission and handle the submission manually, but then the form would reload the current page and skip over some PHP I had before the form code that I neglected to mention:
if (isset($_POST[Submit]))
{
// do registration things
}
I ended up changing the $_POST[Submit] to
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// do registration things
}
removing the onsubmit attribute from my form:
<form name="form5" method="post" action="" id="newform">
and moving it to my submit button:
<input onClick="return billingfunction1();" type="submit" value="Submit"
name="Submit" class="submit_btn">
My new callback function will submit the form manually under the success condition:
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
result = response.split('_');
alert(result[0]);
if(result[0]=="Your Payment has completed successfully") {
console.log("Payment Success");
document.forms["form5"].submit();
} else {
console.log("Payment Failed, Aborting form submission.");
}
}
Everything seems to be working as it should. Thanks so much for your help!

You can just add a submit listener to the form
$("#newform").submit(function(){...})
Prevent the default action
event.preventDefault()
And submit the form manually
$("#newform").submit()
if the condition is meet when the response to the AJAX call comes back.

emphasized text
function billingfunction1() {
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var cardtype = $.trim($("#cardtype").val());
var maxlen = 16;
var digits = cardnumber.toString().length;
var submiteval;
if (cardtype == '') {
// alert("Enter Card Type");
$('#cardtype_msg').html('Enter Card Type.');
$('#cardtype').css('border','1px solid #28a616');
$('#cardtype').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else if (nameoncardfirst == '') {
//alert("Enter Name On Card");
$('#nameoncardfirst_msg').html('Enter First Name On Card.');
$('#nameoncardfirst').css('border','1px solid #28a616');
$('#nameoncardfirst').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else if (nameoncardlast == '') {
//alert("Enter Name On Card");
$('#nameoncardlast_msg').html('Enter Last Name On Card.');
$('#nameoncardlast').css('border','1px solid #28a616');
$('#nameoncardlast').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else {
$.ajax({
url: 'edit_billing2.php',
data: "nameoncardfirst=" + nameoncardfirst+ "&nameoncardlast=" + nameoncardlast + "&street_address2=" + street_address2 +"&city2=" + city2 +"&state=" + state +"&zip=" + zip + "&cardnumber=" + cardnumber + "&expirationdate=" + expirationdate + "&cvv=" + cvv + "&cardtype=" + cardtype+ "&amount=" + amount + "&gender=" + gender + "&first_name=" + first_name + "&last_name=" + last_name + "&address=" + address + "&address2=" + address2 + "&city=" + city + "&post_code=" + post_code + "&country=" + country + "&mobile=" + mobile + "&email=" + email + "&newsletter=" + newsletter + "&make=" + vehicle + "&model=" + model + "&model_year=" + model_year,
success: myCallback
});
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
//alert(response);
result = response.split('_');
//alert("Successfully Saved");
alert(result[0]);
if(result[0]=="Your Payment has completed successfully")
{
console.log("Payment Success");
submiteval = true;
document.forms["form5"].submit();
}
else
{
console.log("Payment Failed, Aborting form submission.");
submiteval = false; //show error to the user instead of returning false
}
return submiteval;
}
}
<form name="form5" method="post" action="" id="newform">
<input type="button" value ="submit" onClick="billingfunction1();" />
</form>
Assign billingfunction1 to onclick event instead of submit.
use document.forms["form5"].submit() to manually submit the form after validating the response from server.

$.ajax has a option named beforeSend(func). U can validate ur data in this func, and return false to cancel ajax.

Related

Using validation to prevent user from adding to the database if limit has been reached

I'm currently trying to get some validation for my project and at the moment I'm currently stuck on preventing the user from being able to add a new amount to the database if the amount has reached it's maximum. I'm using Ajax append to display the data on the page and using a form to add more to the total quantity.
<script>
$(document).ready(function() {
var url = window.location.href;
var id = url.substring(url.lastIndexOf('=') + 1);
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getstockitem?id=' + id,
dataType: "json",
success: function(data) {
if (data) {
for (let i = 0; i < data.length; i++) {
console.log(data);
$("#itemName").append($('<p class="itemStaticText">Name: </p><p class="itemInfoText">' + data[i].stock_name + '</p>'));
$("#itemDescription").append($('<p class="itemStaticText">Description: </p><p class="itemInfoText itemDescriptionText">' + data[i].stock_description + '</p>'));
$("#itemQuantity").append($('<p class="itemStaticText">Quantity: </p><p class="itemInfoText" id="quantity">' + data[i].stock_quantity + '</p>'));
$("#itemShelf").append($('<p class="itemStaticText">Shelf Number: </p><p class="itemInfoText">' + data[i].shelf_number + '</p>'));
$("#itemRack").append($('<p class="itemStaticText">Rack Letter: </p><p class="itemInfoText">' + data[i].rack_letter + '</p>'));
$("#itemPrice").append($('<p class="itemStaticText">Price (£): </p><p class="itemInfoText">' + data[i].stock_price + '</p>'));
}
}
}
});
});
</script>
The code for the validation shown below:
function validateQuantity() {
var quantity=document.quantityForm.quantity.value;
var checkQuantity=document.getElementById("quanitity").value;
if (isNaN(quantity)){
alert("Please enter a valid number!");
document.quantityForm.quantity.focus();
return false;
}else if (quantity > 1000){
alert("Please enter a number below 1,000!");
document.quantityForm.quantity.focus();
return false;
} else if (checkQuantity > 1000) {
alert("You have reached maximum capacity!");
document.quantityForm.quantity.focus();
return false;
} else {
return true;
}
}
At the moment even if the total amount is above 1,000 it still allows the user to add more into the database, is there something I'm missing or not doing right as I'm unable to figure out how to prevent the user from adding more into the database if the maximum amount has been reached through validation.

not getting to my else in jquery javascript

net mvc application and I am trying to do some validation when someone clicks a button. Here is the code.
function productVerify() {
var intQty = $("#txtQty").val();
var strItemName = $("#item_Name").val();
var strItemDescription = $("#item_Description").val();
var intItemID = $("#item_ID").val();
var intItemPrice = $("#item_Price").val();
var strImgUrl = $("item_ImgUrl").val();
var intQty = $("#txtQty").val();
if (intQty < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
}
else {
//post into cart
alert(strItemName + " " + strItemDescription + " " + intItemID + " " + intItemPrice + " " + strImgUrl + " " + intQty + " " + "I got this far.....! good job")
}
}
this works in jsfiddle but for some reason it does not fully work in my mvc application. it does work on the first if because if I put a 0 in my text box I get the first alert, but nothing happens on the else inside my mvc application. This one part seems so easy, but it is killing me any help would be appreciated.
make sure you using a number in your if statement
//if !num
if (parseInt(intQty) == NaN) {
alert("Please enter a number");
return false;
} else {
//if < 1
if (parseInt(intQty) < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
//if >= 1
} else {
//do something
}
}

AJAX call data returned from mvc function is undefined

I know this has been asked 1000 times before but I have hit a brick wall with this.^have created a web application that inserts user data and feedback for the user and the code below is basically part of the PhoneGap application. The strange thing is that the code works perfectly in a web browser but not in Phonegap (output iPad via Xcode).
Therefore would someone know why I am getting an undefined error for the following AJAX call, just after the success callback and the alert(data.ResultId). , any help is appreciated.
Thank you!
// POST: /Result/Create
[HttpPost]
public ActionResult Create(Result result)
{
if (ModelState.IsValid)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (Request.IsAjaxRequest())
{
int ResultId = result.ResultId;
try
{ //valid database entry..send back new ResultId
return Json(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
return Json(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
}
return RedirectToAction("Index");
}
return View(result);
}
Insert QnA
function InsertQnA() {
//hardcoded for testing
Q1 = 10;
Q2 = 10;
Q3 = 10;
Q4 = 10;
Q5 = 10;
Q6 = 10;
Q7 = 10;
Q8 = 10;
Q9 = 10;
Q10 = 10;
localStorage.setItem("Total",100);
localStorage.setItem("CaseStudy", 1);
localStorage.setItem("UserId",1);
Attempts = "1";
////////////////
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
// dataType : "json",
success: function (data) {
alert(data.ResultId);
if (data.Success==true) {
}
else if (data.Success==false) {
viewModel.UserId("Your entry has not been saved, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
The problem was that I was tying to use the same ActionResult to serve an MVC view as well as an htlm5 cordova iOS app. I got round this by copying the ActionResult but changing the return type to a string, note the code looks a bit different in the action, however the original worked fine too. Many thanks to all who posted
[HttpPost]
public string CreateResult(Result result)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (result == null)
{
// User entity does not exist in db, return 0
return JsonConvert.SerializeObject(0);
}
else
{
// Success return user
return JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}
}
AJAX
$.ajax({
url: Domain + '/Result/CreateResult',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
try {
if (data != 0) {
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href=evaluation.html target=_self>evaluation.<a/>");
//reset locals
ResetLocalStorage();
//count number of entities for User
CountUserEntitiesInResults();
}
else
{
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});​

Document.Ready function doesn't seem to be working

Right now I have username and password saved in cookies. My goal is to send that data to my server and then the server will send back response and I will display the response on my webpage. But before I do that I used alert() to see if it is working.
I think something is wrong with the JS:
$(document).ready(function () {
var messageType = "3";
var cookie_name = "username";
var cookie_name2 = "password";
var YouWrote = getName(cookie_name);
var YouWrote2 = getName2(cookie_name2);
var userName = YouWrote;
var password = YouWrote2;
auth(messageType, userName, password);
});
function auth(messageType, userName, password) {
$.ajax({
type: "POST",
//SEND TO SERVER URL
url: "######",
dataType: 'json',
async: false,
data: '{"messageType": "' + messageType + '", "userName": "' + userName + '", "password" : "' + password + '"}',
error: function (xhr, error) {
alert('Error!');
},
success: function (data, textStatus, jqXHR) {
alert(data.details + '\nHello ' + data.clientInfo.firstName + ' ' + data.clientInfo.lastName + '. \nBalance:' + data.clientInfo.balance);
}
})
}
These two functions will help me get the cookie data saved (this works, I have tested it):
function getName() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote = document.cookie.substring(namestart, nameend);
return YouWrote;
}
}
}
function getName2() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name2);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote2 = document.cookie.substring(namestart, nameend);
return YouWrote2;
}
}
}
I turned my server off on purpose because I want to see if it will show alert("Error!"). It doesn't which means the functions aren't running properly in the document.ready.
Is there an obvious issue that I'm missing? Any help will be much appreciated.
Your functions will need to have input argument specified:
function getName(cookie_name){ ... };
function getName2(cookie_name2){ ... };

Submit form via Ajax

So, I followed a tutorial here to be able to submit a form with ajax. I followed the tutorial exactly (atleast I thought I did) and when I try to submit the form the page just refreshes and it never gets to the php script to send it to the database.
The script that I am using is below:
$(function () {
$(".button").click(function () {
$(function () {
$('.error').hide();
$("#submit_btn").click(function () {
//validate and process form here
$('.error').hide();
var firstname = $("input#firstname").val();
if (firstname == "") {
$("label#firstname_error").show();
$("input#firstname").focus();
return false;
}
var lastname = $("input#lastname").val();
if (lastname == "") {
$("label#lastname_error").show();
$("input#lastname").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var pin = $("input#parent_pin").val();
if (pin == "") {
$("label#parent_pin_error").show();
$("input#parent_pin").focus();
return false;
}
var login = $("input#login").val();
if (login == "") {
$("label#login_error").show();
$("input#login").focus();
return false;
}
var passwd = $("input#passwd").val();
if (passwd == "") {
$("label#passwd_error").show();
$("input#passwd").focus();
return false;
}
var cpasswd = $("input#cpasswd").val();
if (cpasswd == "") {
$("label#cpasswd_error").show();
$("input#cpasswd").focus();
return false;
}
var user_type = $("input#user_type").val();
if (user_type == "") {
$("label#user_type_error").show();
$("input#user_type").focus();
return false;
}
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login='
login + '&passwd='
passwd + 'user_type' = user_type;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "studentAccess/files/AddNewUser.php",
data: dataString,
success: function () {
$('#form-body').html("<div id='message'></div>");
$('#message').html("<h2>New User Added Successfully!</h2>");
}
});
});
});
});
});
The error that I am receiving in Google Chrome's console is:
Uncaught SyntaxError: Unexpected identifier AddNewUser.js:65
Line 65 would be:
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' login + '&passwd=' passwd + 'user_type' = user_type;
I'm not sure how to fix this problem because I don't know what the error means. Any help would be great!
UPDATE
<?php
$con = mysqli_connect("");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO members (firstname, lastname, email, login, psswd, user_type)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]', '$_POST[login]', '$_POST[psswd]', '$_POST[user_type]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You have missed + symbols in the #65 line
Should be
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' + login + '&passwd=' + passwd + '&user_type=' + user_type;
Please read http://en.wikipedia.org/wiki/JavaScript_syntax
Remove $(function () { in .button click handler. Now it just registers a handle on button click but not executes it
At the very end of that line you have:
'user_type' = user_type;
It needs to be:
'&user_type=' + user_type;
You may also need to add return false; after your ajax to prevent the page from refreshing (and clearing out your form).
$.ajax({
type: "POST",
url: "studentAccess/files/AddNewUser.php",
data: dataString,
success: function () {
$('#form-body').html("<div id='message'></div>");
$('#message').html("<h2>New User Added Successfully!</h2>");
}
});
return false; //Keep page from refreshing
Further EDIT:
You also have a .click() embedded in a .click(). You cannot click two buttons at one time. You need to change this:
$(function () {
$(".button").click(function () {
$(function () {
$('.error').hide();
$("#submit_btn").click(function () {
to this...
$(function () {
$('.error').hide();
$("#submit_btn").click(function (e) {
e.preventDefault();
...
In the below line, it should be '&user_type=' + user_type; instead of 'user_type' = user_type;
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' login + '&passwd=' passwd + 'user_type' = user_type;
Also, if the button is a submit button, you should prevent the default form submit action using event.preventDefault(); within the button's click event.
In addition, the first two lines of code is not required. I have commented them out.
/*$(function () {
$(".button").click(function () {*/
$(function () {
$('.error').hide();
$("#submit_btn").click(function (event) {
event.preventDefault();
//rest of your current validation code should be put here.
});
});

Categories