Ajax JSON malfunction - javascript

EDIT:
So I ended up with this code here, but as always, can't get it to work properly.
Basically it has to check that all input fields are filled, once this check is true, it calls the JSON url to check validity of the VAT number. If the VAT number check returns true, submits the form, else it inform the customer that there is an error and let the customer choose if to ignore the exception (then submits) or cancel submission and stay on the page.
Here is the JS code, and below is the JSON returned from the call.
$(document).ready(function() {
$('#create_customer').submit(function(){
var canSubmt = true;
$("form#create_customer :input").each(function(){
var input = $(this);
if($(input).val() == '') {
$(input).css("border",'1px solid red');
canSubmt = false;
}else{
$(input).css("border",'1px solid #000');
}
});
if(!canSubmt){ $("#errMsg").text("Errors detected! Please check your form and try again.").show().fadeOut(7000); return canSubmt; }
var vatNum = document.getElementById('VatNum').value;
var validVat;
var vatConfirm;
$.getJSON("http://apilayer.net/api/validate?&access_key=<api-key>&vat_number="+vatNum, function(response) {
validVat = response.valid;
})
.fail(function(){
console.log("failed");
});
if (!validVat) { vatConfirm = confirm("Your VAT number doesn't seem to be valid or in a correct format!\nDo you wish to continue anyway?"); }
if (!vatConfirm) { canSubmt = false; }
return canSubmt;
});
});
and the JSON data, from which I only need the "valid" key:
{ "valid": true, "format_valid": true, "query": "LU26375245", "country_code": "LU", "vat_number": "26375245", "company_name": "AMAZON EUROPE CORE S.A R.L.", "company_address": "5, RUE PLAETIS L-2338 LUXEMBOURG" }
any idea on how to get this working?

Ther're two issues:
Ajax is asynchronous, so before it returns the value of validVat execution probably has already reached the return statement
validVat's scope is inside the ajax function so it will undefined on the line "return ..."
The simplest thing you could do, is to make the ajax request synchronous, see following please:
var validVat = false;
$.ajax({
var vatNumber = document.getElementById("VatNum").value;
url: 'http://apilayer.net/api/validate?access_key=6ab1579cc9e968a65429d7f351375f35&vat_number='+vatNumber,
dataType: 'jsonp',
async: false,
success: function(json) {
// Access and use your preferred validation result objects
if (!json.valid) {
var r = confirm("Your VAT number doesn't seem to be valid or in a correct format!\nDo you wish to continue anyway?");
if (r == true) {
validVat = true;
} else {
validVat = true;
}
}
}
});
return validVat;
The best thing instead, should to use the callback function in order to submit the form or do anything you need after the response of ajax request.
Here's a complete example with a mock of ajax request, please see following:
var validated = false;
$("form").submit(function( event ) {
if(!validated){
event.preventDefault();
var mock = {
ajax: function() {
return mockAjax({
success: $("#test").val() === "correct",
response: { ok: $("#test").val() === "correct" },
timeout: 500
});
}
};
mock.ajax()
.done(function(valid) {
if(valid) {
$("#err").text("Validated... do submit").show();
validated = true;
return $("form").submit();
} else {
event.preventDefault();
}
})
.error(function(json) {
$("#err").text("Not valid!").show().fadeOut(1000);
});
}
});
function mockAjax(options) {
var that = {
done: function done(callback) {
if (options.success)
setTimeout(callback, options.timeout, options.response);
return that;
},
error: function error(callback) {
if (!options.success)
setTimeout(callback, options.timeout, options.response);
return that;
}
};
return that;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type 'correct' to validate.</p>
<form action="javascript:console.log( 'success!' );">
<div>
<input id="test" type="text">
<input type="submit">
</div>
</form>
<span id="err"></span>
I hope it helps you, bye.

Related

How can I call my validate function before sending my ajax when a button is clicked?

Hello everyone I have a table that's dynamically generated from database.
This is the table.
I have all the code that works fine,but I only need proper timing of execution
1) Check if all mandatory fields are populated on button click, if not don't send ajax.
2) When all mandatory fields are populated on button click then call ajax and send proper values to c# and later to database.
First I need to check if all mandatory fields are filled in(check Mandatory column(yes or no values):
$(function () {
$("#myButton").on("click", function () {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
})
});
If not don't call ajax and send values. If all fields are populated then call ajax to send values to c#.
This is the ajax code that takes values from filed and table and send's it to c# WebMethod and later to database.
$(function () {
$('#myButton').on('click', function () {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
});
});
I need code to execute first mandatory fields and when they are all filled in then call ajax part of the code!
Can anyone please help !
If you need more explanation just ask !
Thanks in advance !
Update Liam helped allot me but ajax is not working on button click.
function validate() {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
}
function sendAjax() {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
}
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
})
});
If you want to execute these in order why don't you just add one click handler that calls each function:
function validate(){
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
....etc.
}
function sendAjax(){
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
..etc.
}
$(function () {
$('#myButton').on('click', function () {
validate();
sendAjax();
}
});
Seems it would make sense if your validate function actually returns true or false if your form was valid too. then you could:
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
}
});
I'm not really sure why your doing this:
// Mark it with required attribute
target.prop("required", true);
when you validate? If you just add this into your HTML it will handle required. adding it here seems a bit strange. I'm guessing your not actually submitting the form? It'd make more sense to add the validation message yourself rather than use this attribute.
Your codes not working because your not returning anything from your validate function. It's not 100% clear to me what is valid and what isn't so I can't alter this. But you need to add return true; for valid cases and return false;for invalid cases for the if statement if (validate()){ to work.

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

Jquery Form on submit show success message

I have a form that uses Jquery to show a message for
*field required error message
I am trying to get it to show a success message if the form is submitted.
The form submits as long as the req fields are filled in.
Does anyone know how I can modify this code to show the "success" div if
all the "req" fields are filled out?
Thanks
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit( validateform );
$('$name').submit();
});
});
submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#form id').slideDown('slow'),
<!-- RESET THE FORM FIELDS AFTER SUBMIT STARTS HERE-->
$("#form")[0].reset();
<!--RESET THE FORM FIELDS AFTER SUBMIT ENDS HERE--->
}
});
}
There are two simple ways that will allow you to render a success message. You can either use ajax with the callback success function, or if you want a full post, you you can check at the top of your file if a certain POST was set, and if so, render a success message.
Here is an example of checking POST:
if(isset($_POST['name attribute posting'])) {
$util->showSuccessMessage();
//OR echo "<div class='popup'></div>"
}
And here is an example of using Ajax's success callback function:
function submitForm() {
$.ajax({
url : 'this_file.php',
type: 'POST',
success : showSuccessMessage //function call
})
}
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");
$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit(function()
{
if( validateform)
{
$('$name').submit();
}
} );
});
});
reference submit

How to save var value outside ajax success function?

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.

jQuery Validator -- custom method does not hide error when valid

I have a custom validator checking a value against a database of acceptable values via an ajax request. I thought at first it wasn't hiding the error message because the request was being done asynchronously, so then it could perhaps fail to return true or false in time for the validator to recognize this.
I turned async off and the error message still remains shown. How can I get this to go away?
Through console logging it does return true, yet the error message still remains. I tried to explicitly hide the message, but the validator still assumes false and fails to submit.
jQuery.validator.addMethod("validZip", function(value, element){
var _id = $(element).attr("id");
$.ajax({
url: '/xpress/wp-admin/admin-ajax.php',
data: {action:"test_checkZip", zip:value},
type:"POST",
asyc: false,
success: function(response){
if (response== 0){
return false;
} else {
//$("label[for="+_id+"][class=error]").hide();
return true;
}
}
});
}, '*');
As Nicola pointed out, there's a typo in your callback.
Apart from that it's the callback function that is returning true/false, so actually your validZip function is still returning 'undefined'.
Try this:
jQuery.validator.addMethod("validZip", function(value, element){
var _id = $(element).attr("id");
var isValid = false;
$.ajax({
url: '/xpress/wp-admin/admin-ajax.php',
data: {action:"test_checkZip", zip:value},
type:"POST",
asyc: false,
success: function(response){
isValid = response!= 0;
}
});
return isValid;
}, '*');
Well i think you are checking against result shouldn't you check against response?
success: function(response){
if (response == false){
return false;
} else {
//$("label[for="+_id+"][class=error]").hide();
return true;
}
}
Could it be because you have:
asyc: false,
as opposed to:
async: false,
You used an incorrect answer's code from your previous question, See my answer in that question to see what's wrong. Anyway you should do like this:
jQuery.validator.addMethod("validZip", function(value, element){
var _id = $(element).attr("id");
var return_value;
$.ajax({
url: '/xpress/wp-admin/admin-ajax.php',
data: {action:"test_checkZip", zip:value},
type:"POST",
async: false,
success: function(response){
if (result == 0){
return_value = false;
} else {
//$("label[for="+_id+"][class=error]").hide();
return_value = true;
}
}
return return_value; //HERE you have to return
});
}, '*');
The problem is that you were returning you values inside a nested function, not your validator function.
Hope this helps. Cheers

Categories

Resources