I use jquery to validate the form, check the math-captcha and finally, send a mail.
The validation works fine and the mail works fine. There is only one problem. When my ajax returns false, the bool validCaptcha keeps always true...
$(document).ready(function() {
$("#confirm").on("click", function(e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function() {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function() {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function() {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
validCaptcha = false;
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
}
}
});
//Send email
if (validName == true && validEmail == true && validMessage == true && validCaptcha == true) {
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
}
else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
} else {
reloadCaptcha();
$("#inputcaptcha").val("");
}
});
});
In Firebug I see I get a 'false' back from checkCaptcha.php when e.g. I left the field blank of entered a wrong code.
checkCaptcha.php
session_start();
if ( !empty($_POST['inputcaptcha']) ) {
if ( $_POST['inputcaptcha'] == $_SESSION['security_number'] ) {
echo 'true';
}
else {
echo 'false';
}
}
else {
echo 'false';
}
To check I first checked the result-value from the captcha-ajax
alert(result)
//returned false as it should when leaving blank or entering wrong value
Then before calling the mail-ajax I called all bools
alert('validName='+validName+' & validEmail='+validEmail+' & validMessage='+validMessage+' & validCaptcha='+validCaptcha);
//validCaptcha was true, even when result was false...
What do I not see??
Simply put you can't do that since the validate captcha is an asynchronous request,
Instead you can move the email code to the validate captcha success handler like
$(document).ready(function () {
$("#confirm").on("click", function (e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function () {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function () {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function () {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
if (validName == true && validEmail == true && validMessage == true) {
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
reloadCaptcha();
$("#inputcaptcha").val("");
} else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
}
}
});
}
});
});
Related
** i am trying to do save login details and it works but when signin(true) fuction called page get reload infinity times **
signin(true)
// doing sign in
function onlogin(dataResult, is_check_login) {
$("#preloader").show();
var dataResult = JSON.parse(dataResult);
if (dataResult.statusCode == 200) {
$("#preloader").hide();
var signedin_user_id = dataResult.row_id;
// open dashboard if already logged in
window.location.href = '../page/index.html';
document.getElementById("dashboard_name").innerHTML = dataResult.name;
} else if (dataResult.statusCode == 201) {
$("#preloader").hide();
if (is_check_login) {
//open sign in form if not logged in
window.location.href = '../page/signin.html';
} else {
$("#preloader").hide();
console.log('invalid login');
}
}
}
function sign_in(is_check_login = false) {
var signin_email = $('#signin_email').val();
var signin_password = $('#signin_password').val();
if (is_check_login || (signin_email != "" && signin_password != "")) {
$.ajax({
url: `https://www.name.com/page/php/${is_check_login ? "checklogin" : "login"}.php`,
type: "POST",
data: {
signin_email: signin_email,
signin_password: signin_password
},
cache: false,
success: function (result) {
onlogin(result, is_check_login);
}
});
} else {
alert('Please fill all the field !');
}
}
i have these two jquery functions and one of them is not getting called.but when i comment one of them the other one gets called and vice-versa.
1st
$(function() {
$("[id*=tvAi1] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("#SaveButton").bind("click",
function (e) {
$("#hdMobile").val("");
var tv = document.getElementById("<%= tvAi1.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
}
if ($("#hdMobile").val() == "" || $("#hdMobile").val() == null) {
$("#hdMobile").val(chkArray[i].value);
} else {
$("#hdMobile").val($("#hdMobile").val() + "," + chkArray[i].value);
}
}
}
}
});
});
2nd one
$(function() {
$("[id*=tvAi] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the SMSService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("[id*=tvAi] input[type=radio]").bind("click",
function() {
//hdSms
var parentDIV = $(this).closest("DIV");
if ($(this).is(":checked")) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert("Please enter the Cell Number because you have asked for the SMSService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
$("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
} else {
$("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
}
});
$("#SaveButton").bind("click",
function(e) {
$("#hdSms").val("");
var tv = document.getElementById("<%= tvAi.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the SMSService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
}
if ($("#hdSms").val() == "" || $("#hdSms").val() == null) {
$("#hdSms").val(chkArray[i].value);
} else {
$("#hdSms").val($("#hdSms").val() + "," + chkArray[i].value);
}
}
}
}
});
});
I tried combining them both but didnt helped.I want both of them to be called according to div enabled/disabled from my code-behind.Newbie here.Help Appreciated.
You may call your anonymous functions to set the jQuery's methods. Try something like this for the 2 functions:
$(function() {
/*Do stuff... */
})();
In your code, you set two anonymous functions (or closures). This functions will be never call (at least in your example). They only can be call (in your example) if you put the braces at the end (with some optional function's parameters).
Advantages:
Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.
Consequently, you can use a closure anywhere that you might normally
use an object with only a single method.
Please check the documentation.
I am using prototype js and jquery in noconflict mode. It worked for all my code except for one.
I have done
<script type="text/javascript" src="js/jquery/jquery-2.1.3.min.js"></script>
<script>
$.noConflict();
///////////////////////////////////////////////////////////////////////////////
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
///////////////////////////////////////////////////////////////////////////////
//Here is the wall post code
var form = {
post : {
beforeSubmit: showRequest,
success: showResponse,
resetForm: true
}
};
$.fn.showLoader = function(){
$(this).removeClass('hide');
}
$.fn.hideLoader = function(){
$(this).addClass('hide');
}
//The code continues
$(document).ready(function(){
$('.floader').showLoader();
$('.facebook-share-box').ajaxForm(form.post);
$.get('profile_wall.php',function(data){
$('.wall').html(data);
$('.floader').hideLoader();
});
$("#geocomplete").geocomplete({
map: ".map_canvas",
details: "form",
types: ["geocode", "establishment"]
});
$('body').delegate('#shareType','click', function(e) {
e.preventDefault();
var positionArray = {};
positionArray['status'] = 0;
positionArray['photos'] = 80;
positionArray['videos'] = 160;
positionArray['location'] = 231;
$('.video').hideLoader('hide');
$('.image').hideLoader('hide');
$('.place').hideLoader('hide');
$('.shareType').val($(this).attr('class'));
$('.arrow').css("left", positionArray[$(this).attr('class')]);
if($(this).attr('class') == 'videos') {
$('.video').showLoader('hide');
$('.image').hideLoader('hide');
$('.place').hideLoader('hide');
}
if($(this).attr('class') == 'photos') {
$('.video').hideLoader('hide');
$('.image').showLoader('hide');
$('.place').hideLoader('hide');
}
if($(this).attr('class') == 'location') {
$('.video').hideLoader('hide');
$('.image').hideLoader('hide');
$('.place').showLoader('hide');
}
return false;
});
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
loadData();
}
});
});
function showRequest(formData, jqForm, options) {
type = $('.shareType').val();
for (var i=0; i < formData.length; i++) {
/*
if (!formData[i].value && formData[i].name == 'message') {
alert('Message could not be empty');
return false;
}
*/
if(type == 'photos') {
var fileName = document.getElementById("image").value
if (fileName == "") {
alert("Browse to upload a valid File with png/jpg/gif extension");
return false;
}
else if (fileName.split(".")[1].toUpperCase() == "PNG") {
}
else if (fileName.split(".")[1].toUpperCase() == "JPG") {
}
else if (fileName.split(".")[1].toUpperCase() == "JPEG") {
}
else if (fileName.split(".")[1].toUpperCase() == "GIF") {
}
else {
alert("File with " + fileName.split(".")[1] + " is invalid. Upload a validfile with png/jpg/gif extensions");
return false;
}
}
if(type == 'videos') {
if (!formData[i].value && formData[i].name == 'videoUrl') {
alert('Video Url could not be empty');
return false;
}
video = validateVideoUrl();
if(video == false){
alert('Not a valid youtube/vimeo video URL');
return false;
}
}
if(type == 'location') {
if (!formData[i].value && formData[i].name == 'location') {
alert('Place could not be empty');
return false;
}
if((!formData[i].value && formData[i].name == 'lat') || (!formData[i].value && formData[i].name == 'lng')){
alert('Not a valid place');
return false;
}
}
}
btn = $('#btn-share');
btn.button('loading');
}
//The response is shown here
function showResponse(responseText, statusText, xhr, $form) {
$('#wall-append').prepend(responseText);
btn.button('reset');
}
//This enable to validate url video
function validateVideoUrl(){
var url = $('#videoUrl').val();
var regYoutube = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var regVimeo = /^.*(vimeo\.com\/)((channels\/[A-z]+\/)|(groups\/[A-z]+\/videos\/))?([0-9]+)/;
if(regYoutube.test(url) || regVimeo.test(url)) {
return true;
}else{
return false;
}
}
function loadData()
{
$('div.postloader').html('<img src="img/loader.gif">');
$.post("profile_get_data.php?lastID=" + $(".post-list:last").attr("id"),
function(data){
if (data != "") {
$(".post-list:last").after(data);
}
$('div.postloader').empty();
});
};
///////////////////////////////////////////////////////////////////////////////
});
</script>
But still it is not working. I don't know why it gives me an infinite load and then it gives me
Error: Permission denied to access property 'toString'
Please how to put jquery in noconflict mode with this ?
I have been struggle with this now for two days and I do not know where the problem is.
When I leave the textbox the Ajax call is correct and the result are returned as a true or false and the success: function is executing.
The problem is that the image and error text is not displaying next to the textbox. If I type in more than 50 characters in the textbox the "Must be under 50 characters" message is showing but it I type in a user name that already exist the message is not showing.
What am I missing? Any suggestions?
I use a DevExpress Text Box
Html.DevExpress().Label(
edtSettings =>
{
edtSettings.ControlStyle.CssClass = "label";
edtSettings.Text = "User Name:";
edtSettings.AssociatedControlName = "UserName";
}
)
.Render();
Html.DevExpress().TextBox(
edtSettings =>
{
edtSettings.Name = "UserName";
edtSettings.ControlStyle.CssClass = "editor";
edtSettings.ShowModelErrors = true;
edtSettings.Width = 100;
edtSettings.Properties.ValidationSettings.Assign(IserValidationHelper.UserNameValidationSettings);
edtSettings.Properties.ClientSideEvents.Validation = "OnNameValidation";
edtSettings.ControlStyle.BackColor = System.Drawing.Color.LightYellow;
}
)
.Bind(DataBinder.Eval(IserUser, "UserName"))
.Render();
I have the following JavaScript.
<script type="text/javascript">
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/Admin/CheckUsername',
dataType: 'json',
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 50) {
e.isValid = false;
e.errorText = "Must be under 50 characters";
}
}
I have the following method in my controller.
[HttpPost]
public ActionResult CheckUsername(string userName)
{
bool status = WebSecurity.UserExists(userName);
return Json(new { result = status });
}
The problem was with my $.ajax call. I had to include the setting async (async:false,) as the default async is true. It is working now correctly.
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/ISERAdmin/CheckUsername',
dataType: 'json',
async:false,
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 56) {
e.isValid = false;
e.errorText = "Must be under 56 characters";
}
}
I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
var data = 'user='+ fullname;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
}
});
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}