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 ?
Related
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 have two JavaScript files. One is running validation, and other have ajax plugin that sends form after validation.
When I attached these files in the header section, then they simultaneously run, but if I attach these two files in the body, then validation runs as it should but ajax call not working.
There is no any error on the console as well.
..
What you people suggests?
AjaxCall.js
$(document).ready(function() {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: 'quoteProcess.php', // override for form's 'action' attribute
type: 'post', // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
};
// bind 'myForm' and provide a simple callback function
$('#testform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.modal').show();
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
$('.modal').hide();
alert( '\n\nYour Quote has been Recieved ! \n' + responseText +
'\n');
window.location.replace("http://localhost/lamozine/quote.php");
}
validation.js
(function($){
var functions = {
reset: resetValidation
};
var settings;
var _reqForm;
var _indicatorTemplate = '<span class="error-indicator" role="alert" aria-live="assertive" aria-hidden="true"></span>';
var _summaryTemplate = '<div id="errorSummary" class="alert alert-danger" role="alert" aria-live="assertive" tabindex="-1"><p>{0}</p></div>';
var _validationTypes = {
required: {msg: ' is required' },
tel: {msg: ' is not a valid phone number' },
email: {msg: ' is not a valid email address' },
date: {msg: ' is not a valid date'},
number: {msg: ' is not a valid number'}
};
$.fn.attrvalidate = function() {
if (!this.is('form')) {
return this;
}
if (typeof arguments[0] === 'string') {
var property = arguments[1];
var newArgs = Array.prototype.slice.call(arguments);
newArgs.splice(0, 1);
functions[arguments[0]].apply(this, newArgs);
} else {
setupFormValidation.apply(this, arguments);
}
return this;
};
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function setupFormValidation(options){
settings = $.extend({
showFieldIndicator: true,
showErrorSummary: true,
errorSummaryMsg: 'Please fix the following issues before continuing:',
validateTel: true,
telRegex: /^\+*[\d-()]{7,20}$/,
validateEmail: true,
emailRegex: /^(\S+#\S+)*$/,
validateDate: true,
validateNumber: true
}, options);
_reqForm = this;
initialiseValidation();
$(_reqForm).bind('submit', handleSubmit);
}
function initialiseValidation(){
var _groupsInitialised = [];
$(_reqForm).find('input, select[required], textarea[required]').each(function(){
if (isRadioGroup($(this)) && $(this).is('[required]')) {
var groupName = $(this).attr('name');
if ($.inArray(groupName, _groupsInitialised) === -1) {
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
$(this).parents('fieldset').first().append($(_indicatorTemplate));
}
$(_reqForm).find('input[name="' + $(this).attr('name') + '"]').each(function(){
$(this).change(function(){
handleFieldChanged($(this));
});
});
_groupsInitialised.push(groupName);
}
} else {
if ($(this).is('[required]') ||
(settings.validateTel && $(this).is('input[type="tel"]')) ||
(settings.validateEmail && $(this).is('input[type="email"]')) ||
(settings.validateDate && $(this).is('input[type="date"]')) ||
(settings.validateNumber && $(this).is('input[type="number"]'))){
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
if (($(this).is('input[type="radio"]') || $(this).is('input[type="checkbox"]')) && $(this).next('label').length > 0) {
$(this).next('label').after($(_indicatorTemplate));
} else {
$(this).after($(_indicatorTemplate));
}
}
$(this).change(function(){
handleFieldChanged($(this));
});
}
}
});
}
function handleFieldChanged(elem){
var validationResult = validateField(elem);
if (validationResult.isValid) {
clearFieldError(elem);
} else {
var fieldMsg = getFieldMessage(elem, validationResult.type);
showFieldError(elem, fieldMsg);
}
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$(_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();
}
}
}
function validateField(elem){
if (!elem.is(':visible') || elem.parents('[aria-hidden="true"]').length > 0){
return { isValid: true };
}
if (elem.is('input[type="radio"]')) {
if (elem.is('[required]')){
if (isRadioGroup(elem)) {
return { isValid: ($(_reqForm).find('input[name="' + elem.attr('name') + '"]:checked').length > 0), type: _validationTypes.required };
} else {
return { isValid: elem.is(':checked'), type: _validationTypes.required };
}
} else {
return { isValid: true };
}
} else if (elem.is('input[type="checkbox"]')) {
return { isValid: (!elem.is('[required]') || elem.is(':checked')), type: _validationTypes.required };
} else {
if (elem.is('[required]') && (elem.val() === '')) {
return { isValid: false, type: _validationTypes.required };
} else if (settings.validateTel && elem.is('input[type="tel"]')) {
return { isValid: settings.telRegex.test(elem.val().replace(/ /g, '')), type: _validationTypes.tel };
} else if (settings.validateEmail && elem.is('input[type="email"]')) {
return { isValid: settings.emailRegex.test(elem.val().trim()), type: _validationTypes.email };
} else if (settings.validateDate && elem.is('input[type="date"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(Date.parse(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(Date.parse(elem.prop('max'))) && Date.parse(elem.val()) > Date.parse(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(Date.parse(elem.prop('min'))) && Date.parse(elem.val()) < Date.parse(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.date };
} else if (settings.validateNumber && elem.is('input[type="number"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(parseFloat(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(parseFloat(elem.prop('max'))) && parseFloat(elem.val()) > parseFloat(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(parseFloat(elem.prop('min'))) && parseFloat(elem.val()) < parseFloat(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.number };
} else {
return { isValid: true };
}
}
}
function setFieldName(elem){
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
return;
}
var elemName;
var forLabel = $(_reqForm).find('label[for="' + elem.attr('id') + '"]');
if (forLabel.length > 0 && $(forLabel[0]).text() !== '') {
elemName = $(forLabel[0]).text();
} else {
elemName = elem.attr('name');
}
elem.data('error-name', elemName);
}
function getFieldMessage(elem, resultType){
var elemMsg;
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
elemMsg = elem.data('error-msg');
} else {
elemMsg = elem.data('error-name') + resultType.msg;
}
return elemMsg;
}
function showFieldError(elem, fieldMsg){
if (isRadioGroup(elem)) {
elem.parents('fieldset').first().addClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
} else {
elem.addClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
}
}
function clearFieldError(elem){
if (isRadioGroup(elem)) {
elem.parents('fieldset').removeClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().attr('aria-hidden', true);
}
var firstInGroup = $(_reqForm).find('input[name="' + elem.attr('name') + '"]').first();
var summaryItem = $('#errorSummary li a[data-field="' + firstInGroup.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
} else {
elem.removeClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().attr('aria-hidden', true);
}
var summaryItem = $('#errorSummary li a[data-field="' + elem.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
}
}
function showErrorSummary(errorMsgList){
var errorSummary = $(_summaryTemplate.replace('{0}', settings.errorSummaryMsg));
var errorList = $('<ul></ul>');
for (var i=0; i < errorMsgList.length; i++) {
var errorLink = $('' + errorMsgList[i].msg + '');
errorLink.click(function(){ jumpToElem($(this).data('field')); return false; });
var errorItm = $('<li></li>');
errorItm.append(errorLink);
errorList.append(errorItm);
}
errorSummary.append(errorList).prependTo($(_reqForm));
errorSummary.focus();
}
function isRadioGroup(elem){
return (elem.is('input[type="radio"]') && typeof(elem.attr('name')) !== 'undefined' && elem.attr('name') !== '');
}
function jumpToElem(fieldId){
$(_reqForm).find('#' + fieldId).focus();
}
}(jQuery));
I am not clear with your question very well but if you want to load one script file after loading an another script file. You can simple load using $.when() and $.getScript() jquery functions like this.
$.getScript() will load javascript file asynchronously and .done() call back of $.when() method will continue after the loading script done.
This is a very simple sample.
<html>
<head>
<script src="/jquery.min.js"></script>
</head>
<body>
<script>
$.when(
$.getScript("/mypath/validation.js")
).done(function(){
$.getScript("/mypath/AjaxCall.js")
});
</script>
</body>
Hope it might help.
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');
}
}
});
}
}
});
}
});
});
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;
}
}
How can I fix this error "missing; before statement" in javascript ?
My HTML Page :
http://etrokny.faressoft.com
My Javascript Code :
http://etrokny.faressoft.com/javascript.php
When assigning a function to a variable, you need a semicolon after the function.
Example: var func = function() { return false; };
Put a semicolon after all statements. JavaScript does it automatically for you when you "forget" one at the end of a line**, but since you used a tool to make everything fit on one line, this doesn't happen anymore.
** it should also be happening when a statement is followed by a }, but it's just bad practice to rely on it. I would always write all semicolons myself.
Actually, you know what, since it's so easy, I did it for you:
function getSelected() {
var selText;
var iframeWindow = window;
if (iframeWindow.getSelection) {
selText = iframeWindow.getSelection() + "";
} else if (iframeWindow.document.selection) {
selText = iframeWindow.document.selection.createRange().text;
}
selText = $.trim(selText);
if (selText != "") {
return selText;
} else {
return null;
}
}
$(document).ready(function () {
function scan_selectedText() {
if (getSelected() == null) {
return false;
}
if (getSelected().length < 25) {
return false;
}
$(document)[0].oncontextmenu = function () {
return false;
};
var result = true;
var selected_Text = getSelected();
selected_Text = selected_Text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
$('#content .para').each(function () {
var accepted_text = $.trim($(this).text());
accepted_text = accepted_text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
if (accepted_text.search(selected_Text) > -1) {
result = false;
}
});
var AllAccepted = "";
$('#content .para').each(function () {
var correntDiv = $.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
AllAccepted = AllAccepted + correntDiv + " ";
});
if ($.trim(AllAccepted).search(selected_Text) > -1) {
return false;
}
if (!result) {
return false;
}
var body = $.trim($('body').text());
body = body.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
var bodyWithoutDivs = body;
$('#content').each(function () {
var correntDiv = new RegExp($.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' '), "");
bodyWithoutDivs = bodyWithoutDivs.replace(correntDiv, '');
});
if (bodyWithoutDivs.search(selected_Text) > -1) {
return false;
}
if (body == selected_Text) {
return true;
}
return true;
}
$(document).mousedown(function (key) {
if (key.button == 2) {
if (scan_selectedText() == true) {
$(document)[0].oncontextmenu = function () {
return false;
};
} else {
$(document)[0].oncontextmenu = function () {
return true;
};
}
}
});
var isCtrl = false;
$(document).keyup(function (e) {
if (e.which == 17) isCtrl = false;
}).keydown(function (e) {
if (e.which == 17) isCtrl = true;
if (e.which == 67 && isCtrl == true) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
});
document.onkeypress = function (evt) {
if (evt.ctrlKey == true && evt.keyCode == 67) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
};
$('*').bind('copy', function (key) {
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
});
});
First thing, start with the raw human-written version of your javascript, you know, the unminimized non-machine-generated version
After you've fixed you've made sure it is free from syntax errors .... and you minimize it, don't make a mistake when copy/pasting