I installed an plugin on my current clean wordpress installation. However I always get the following error as soon as the widget for the plugin gets laoded
TypeError: $ is not a function
I checked the js files for the addon and they all seem to make proper use of jQuery instead of $ also the register_script function requires jquery as dependency
Below you can see the add_action function
if (!is_admin()) {
function woocommerce_ogonecw_add_frontend_css() {
wp_register_style('woocommerce_ogonecw_frontend_styles', plugins_url('resources/css/frontend.css', __FILE__));
wp_enqueue_style('woocommerce_ogonecw_frontend_styles');
true);
wp_register_script('ogonecw_frontend_script', plugins_url('resources/js/frontend.js', __FILE__), array(
'jquery'
));
wp_enqueue_script('ogonecw_frontend_script');
wp_localize_script('ogonecw_frontend_script', 'woocommerce_ogonecw_ajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'woocommerce_ogonecw_add_frontend_css');
frontend.js looks like this
jQuery(function (jQuery) {
var isSubmitted = false;
var CheckoutObject = {
cssClass: '',
successCallback: '',
placeOrder: function() {
var form = jQuery('form.checkout');
var form_data = form.data();
// WGM: Back Button
if(jQuery("input[name=cw-wgm-button-back]").length > 0) {
return true;
}
//WGM: MultiStep
if(jQuery("input[name=wc_gzdp_step_submit]").length > 0) {
if(jQuery("input[name=wc_gzdp_step_submit]").val() == "address"){
return true;
}
}
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
var secondRun = false;
if(jQuery("input[name=ogonecw_payment_method_choice]").length > 0) {
secondRun = true;
selectedPaymentMethodElement = jQuery("input[name=ogonecw_payment_method_choice]");
selectedPaymentMethod = selectedPaymentMethodElement.val();
}
var moduleName = 'ogonecw';
var selectedModuleName = (selectedPaymentMethod != undefined) ?
selectedPaymentMethod.toLowerCase().substring(0, moduleName.length) : '';
onOgoneCwCheckoutPlaceObject = this;
if (moduleName == selectedModuleName) {
form.addClass('processing');
if ( form_data["blockUI.isBlocked"] != 1 ) {
form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
}
this.successCallback = previewAuthorization;
this.cssClass = 'ogonecw-preview-fields';
onOgoneCwCheckoutPlaceObject = this;
if(secondRun) {
this.generateOrder(form, selectedPaymentMethod);
return false;
}
var validateFunctionName = 'cwValidateFields'+selectedPaymentMethod.toLowerCase();
var validateFunction = window[validateFunctionName];
if (typeof validateFunction != 'undefined') {
validateFunction(function(valid){onOgoneCwCheckoutPlaceObject.successCall();}, function(errors, valid){onOgoneCwCheckoutPlaceObject.failureCall(errors, valid);});
return false;
}
onOgoneCwCheckoutPlaceObject.successCall();
return false;
}
},
failureCall: function(errors, valid){
alert(errors[Object.keys(errors)[0]]);
var form = jQuery('form.checkout');
form.removeClass('processing').unblock();
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
},
successCall : function(){
var form = jQuery('form.checkout');
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
onOgoneCwCheckoutPlaceObject = this;
if(selectedPaymentMethodElement.parents('li').find('.ogonecw-validate').length > 0){
var ajaxUrl;
if(typeof wc_checkout_params != 'undefined') {
ajaxUrl = wc_checkout_params.ajax_url;
}
if(typeof checkoutUrl == 'undefined') {
ajaxUrl = woocommerce_params.ajax_url;
}
var separator = ajaxUrl.indexOf('?') !== -1 ? "&" : "?";
ajaxUrl = ajaxUrl+separator+"action=woocommerce_ogonecw_validate_payment_form";
var inputData = getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase());
var postData = "&";
jQuery.each(inputData, function(key, value) {
postData += encodeURIComponent(key)+"="+encodeURIComponent(value)+"&";
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: form.serialize()+postData+ onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
response = jQuery.parseJSON(code);
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch(err ){
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.message ) {
form.prepend(response.message);
} else {
form.prepend(code);
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
}
},
dataType: 'html'
});
return false;
}
else {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
},
generateOrder: function(form, selectedPaymentMethod) {
onOgoneCwCheckoutPlaceObject = this;
var checkoutUrl;
if(typeof wc_checkout_params != 'undefined') {
checkoutUrl = wc_checkout_params.checkout_url;
}
if(typeof checkoutUrl == 'undefined') {
checkoutUrl = woocommerce_params.checkout_url;
}
jQuery.ajax({
type: 'POST',
url: checkoutUrl,
data: form.serialize() + "&" + onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
if (code.indexOf("<!--WC_START-->") >= 0) {
code = code.split("<!--WC_START-->")[1];
}
if (code.indexOf("<!--WC_END-->") >= 0) {
code = code.split("<!--WC_END-->")[0];
}
try {
// Check for valid JSON
response = jQuery.parseJSON( code );
} catch ( e ) {
// Attempt to fix the malformed JSON
var validJson = code.match( /{"result.*"}/ );
if ( null === validJson ) {
throw 'Invalid response';
} else {
response = jQuery.parseJSON(validJson[0]);
}
}
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.successCallback(response, selectedPaymentMethod);
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch( err ) {
if ( response.reload === 'true' ) {
window.location.reload();
return;
}
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.messages ) {
form.prepend( response.messages );
} else {
form.prepend( code );
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
// Trigger update in case we need a fresh nonce
if ( response.refresh === 'true' ) {
jQuery( 'body' ).trigger( 'update_checkout' );
}
jQuery( 'body' ).trigger( 'checkout_error' );
}
},
dataType: 'html'
});
},
};
var getFormFieldValues = function(parentCssClass, paymentMethodPrefix) {
var output = {};
jQuery('.' + parentCssClass + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(paymentMethodPrefix, 0) === 0) {
name = name.substring(paymentMethodPrefix.length);
name = name.substring(1, name.length -1 );
if(this.type == "radio") {
if(this.checked) {
output[name] = jQuery(this).val();
}
}
else{
output[name] = jQuery(this).val();
}
}
});
return output;
};
var generateHiddenFields = function(data) {
var output = '';
jQuery.each(data, function(key, value) {
output += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
return output;
};
var removeNameAttributes= function(cssClass) {
// Remove name attribute to prevent submitting the data
jQuery('.' + cssClass + ' *[name]').each(function (element) {
jQuery(this).attr('data-field-name', jQuery(this).attr('name'));
if(jQuery(this).is(':radio')){
return true;
}
jQuery(this).removeAttr('name');
});
}
var addAlias = function(cssClass){
// Add listener for alias Transaction selector
jQuery('.' + cssClass).parents('li').find('.ogonecw-alias-input-box > select').bind('change', function() {
jQuery('body').trigger('update_checkout');
});
}
var registerCheckoutObject = function(){
bindOrderConfirmEvent(CheckoutObject);
};
var bindOrderConfirmEvent = function (CheckoutObject) {
var form = jQuery('form.checkout');
var attached = form.attr('data-ogonecw-attached');
if (attached != 'true') {
form.attr('data-ogonecw-attached', 'true');
form.bind('checkout_place_order', function() {
return CheckoutObject.placeOrder();
});
return false;
}
};
// We have to make sure that the JS in the response is executed.
jQuery( document ).ready(function() {
if (typeof window['force_js_execution_on_form_update_listener'] === 'undefined') {
window['force_js_execution_on_form_update_listener'] = true;
jQuery('body').bind('updated_checkout', function() {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
}
});
jQuery( document ).ajaxStop(function(event, xhr, settings) {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
var previewAuthorization = function (result, selectedPaymentMethod) {
if(typeof result.redirect !== 'undefined') {
var additionalFields = jQuery('<div class="ogonecw-preview-fields" style="display: none;"></div>');
jQuery('.' + 'ogonecw-preview-fields' + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(selectedPaymentMethod.toLowerCase(), 0) === 0) {
jQuery(additionalFields).append(jQuery(this));
}
});
var redirectUrl;
if ( result.redirect.indexOf( "https://" ) != -1 || result.redirect.indexOf( "http://" ) != -1 ) {
redirectUrl = result.redirect;
} else {
redirectUrl = decodeURI( result.redirect );
}
jQuery.get(redirectUrl, function(data){
var newBodyString = data.replace(/^[\S\s]*<body[^>]*?>/i, "").replace(/<\/body[\S\s]*jQuery/i, "");
var newBody = jQuery("<div></div>").html(newBodyString);
if(newBody.find('.wgm-go-back-button').length > 0){
jQuery('body').html(newBody.html());
jQuery('form.checkout').append(additionalFields);
jQuery('form.checkout').append('<input type="hidden" name="ogonecw_payment_method_choice" value="'+selectedPaymentMethod+'"/>');
jQuery('.wgm-go-back-button').on('click', function() {
jQuery('form.checkout').append('<input type="hidden" name="cw-wgm-button-back" value="back"/>');
});
jQuery('form.checkout').on('submit', function(){
return CheckoutObject.placeOrder();
});
jQuery("html, body").animate({
scrollTop: jQuery("form.checkout").offset().top - 100
}, 1e3);
}
else {
window.location = decodeURI( redirectUrl );
}
});
}
else if(typeof result.ajaxScriptUrl !== 'undefined'){
jQuery.getScript(result.ajaxScriptUrl, function() {
eval("var callbackFunction = " + result.submitCallbackFunction);
callbackFunction(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
});
}
else {
var newForm = '<form id="ogonecw_preview_form" action="' + result.form_action_url + '" method="POST">';
newForm += result.hidden_form_fields;
newForm += generateHiddenFields(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
newForm += '</form>';
jQuery('body').append(newForm);
jQuery('#ogonecw_preview_form').submit();
}
}
});
So what exactly is causing this error since the plugin seems to be setup correctly
Related
I am getting the following error on all browsers while opening the float box and then it cannot be closed. You need to refresh the page. There was no problem before. It was working fine. Now, I've been getting this error ever since I adapted the new design to the site. How can fix this problem? Thank you.
Uncaught TypeError: Cannot read property 'show' of undefined
// disabling/enabling
jQuery.fn.extend({
disable: function() {
this.each(function()
{
this.disabled = true;
if ( this.tagName != 'INPUT' && this.tagName != 'TEXTAREA' && this.tagName != 'SELECT' )
{
this.jQuery_disabled_clone =
jQuery(this)
.addClass('disabled')
.clone()
.removeAttr('id')
.get(0);
jQuery(this)
.hide()
.bind('unload', function(){
jQuery(this).enable();
})
.after(this.jQuery_disabled_clone);
}
});
return this;
},
enable: function()
{
this.each(function()
{
this.disabled = false;
if ( this.jQuery_disabled_clone )
{
jQuery(this.jQuery_disabled_clone).remove();
this.jQuery_disabled_clone = null;
jQuery(this)
.unbind('unload', function(){
jQuery(this).enable();
})
.removeClass('disabled')
.show();
}
});
return this;
}
});
function SK_Exception(message, code)
{
this.toString = function() {
return message;
}
this.getCode = function() {
return code;
}
}
function SK_drawError(err_msg, delay) {
SK_drawMessage(err_msg, 'error', delay);
}
function SK_drawMessage(msg_text, type, delay)
{
if (navigator.appName == 'Microsoft Internet Explorer' && (msg_text == "Virtual gift has been sent" || msg_text == "Hediyeniz başarıyla gönderildi.." || msg_text == "Virtual gift has not been sent" || msg_text == "Hediyeniz gönderilemedi.."))
alert(msg_text);
type = type || 'message';
delay = delay || (1000*10);
if (SK_drawMessage.in_process) {
if (msg_text) {
SK_drawMessage.queue.unshift([msg_text, type, delay]);
}
return;
}
if (!msg_text) {
var item = SK_drawMessage.queue.shift();
if (!item) {
return;
}
msg_text = item[0];
type = item[1];
delay = item[2];
}
SK_drawMessage.in_process = true;
// getting draw position
var $last = jQuery('.macos_msg_node:last');
var top_pos = (!$last.length) ? 0 : $last.position().top + $last.outerHeight() + 2;
var $msg_block =
// creating message block
jQuery('<div class="macos_msg_node macos_'+type+'" style="display: none"></div>')
.appendTo('body')
.html(msg_text)
.prepend('<a class="close_btn" href="#"></a>')
.css('top', top_pos)
.fadeTo(50, 0.1, function() {
jQuery(this).css('display', '');
SK_drawMessage.in_process = false;
SK_drawMessage();
jQuery(this).fadeTo(300, 1, function() {
if (delay > 0) {
window.setTimeout(function() {
try {
$msg_block.fadeOut(2500, function() {
jQuery(this).remove();
});
} catch (e) {alert(e);}
}, delay);
}
});
});
$msg_block.children('.close_btn')
.click(function() {
jQuery(this).parent().fadeOut(100, function() {
jQuery(this).remove();
});
return false;
}
);
}
SK_drawMessage.in_process = false;
SK_drawMessage.queue = [];
/**
* Float box constructor.
*
* #param string|jQuery $title
* #param string|jQuery $contents
* #param jQuery $controls
* #param object position {top, left} = center
* #param integer width = auto
* #param integer height = auto
*/
function SK_FloatBox(options)
{
var fb_class;
if (typeof document.body.style.maxHeight === 'undefined') { //if IE 6
jQuery('body').css({height: '100%', width: '100%'});
jQuery('html').css('overflow', 'hidden');
if (document.getElementById('floatbox_HideSelect') === null) { //iframe to hide select elements in ie6
jQuery('body').append('<iframe id="floatbox_HideSelect"></iframe><div id="floatbox_overlay"></div>');
fb_class = SK_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
jQuery('#floatbox_overlay').addClass(fb_class);
}
}
else { //all others
if (document.getElementById('floatbox_overlay') === null) {
jQuery('body').append('<div id="floatbox_overlay"></div>');
fb_class = SK_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
jQuery('#floatbox_overlay').addClass(fb_class);
}
}
jQuery('body').css('overflow', 'hidden');
this.$container = jQuery('.floatbox_container', '#sk-floatbox-block-prototype').clone().appendTo('body');
this.$header = this.$container.find('.block_cap_title');
if (typeof options.$title == 'string') {
options.$title = jQuery('<span>'+options.$title+'</span>');
}
else {
this.$title_parent = options.$title.parent();
}
this.$header.append(options.$title);
this.$body = this.$container.find('.block_body_c');
if (typeof options.$contents == 'string') {
options.$contents = jQuery('<span>'+options.$contents+'</span>');
}
else {
this.$contents_parent = options.$contents.parent();
}
this.$body.append(options.$contents);
this.$bottom = this.$container.find('.block_bottom_c');
if (options.$controls) {
if (typeof options.$controls == 'string') {
options.$controls = jQuery('<span>'+options.$controls+'</span>');
}
else {
this.$controls_parent = options.$controls.parent();
}
this.$bottom.append(options.$controls);
}
if (options.width)
this.$container.css("width", options.width);
if (options.height)
this.$container.css("height", options.height);
var fl_box = this;
jQuery('.close_btn', this.$container.find('.floatbox_header'))
.one('click', function() {
fl_box.close();
return false;
});
this.esc_listener =
function(event) {
if (event.keyCode == 27) {
fl_box.close();
return false;
}
return true;
}
jQuery(document).bind('keydown', this.esc_listener);
this.$container
.fadeTo(1, 0.1, function()
{
var $this = jQuery(this);
$this.css('display', 'block');
if (options.position) {
$this.css(options.position);
}
else {
var position = {
top:((jQuery(window).height()/2) - ($this.height()/2))/*.ceil()*/,
left:((jQuery(window).width()/2) - ($this.width()/2))/*.ceil()*/
};
$this.css(position);
}
// trigger on show event
fl_box.trigger('show');
$this.fadeTo(100, 1);
});
this.events = {close: [], show: []};
}
SK_FloatBox.detectMacXFF = function()
{
var userAgent = navigator.userAgent.toLowerCase();
return (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1);
}
SK_FloatBox.prototype = {
close: function()
{
if (this.trigger('close') === false) {
return false;
}
jQuery(document).unbind('keydown', this.esc_listener);
if (this.$title_parent && this.$title_parent.length) {
this.$title_parent.append(
this.$header.children()
);
}
if (this.$contents_parent && this.$contents_parent.length) {
this.$contents_parent.append(this.$body.children());
}
if (this.$controls_parent && this.$controls_parent.length) {
this.$controls_parent.append(this.$bottom.children());
}
this.$container.remove();
if (jQuery('.floatbox_container:not("#sk-floatbox-block-prototype .floatbox_container")').length === 0) {
jQuery('body').css('overflow', '');
jQuery('#floatbox_overlay, #floatbox_HideSelect').remove();
}
return true;
},
bind: function(type, func)
{
if (this.events[type] == undefined) {
throw 'form error: unknown event type "'+type+'"';
}
this.events[type].push(func);
},
trigger: function(type, params)
{
if (this.events[type] == undefined) {
throw 'form error: unknown event type "'+type+'"';
}
params = params || [];
for (var i = 0, func; func = this.events[type][i]; i++) {
if (func.apply(this, params) === false) {
return false;
}
}
return true;
}
}
function SK_alert($title, $contents, callback)
{
if (!callback &&
typeof $contents == 'function' &&
$contents.constructor != Array) {
callback = $contents;
}
if (!$contents || $contents == callback) {
$contents = $title;
$title = SK_Language.text('%interface.alert_title');
}
var $ok_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.ok'));
var fl_box = new SK_FloatBox({
$title: $title,
$contents: $contents,
$controls: $ok_btn
});
$ok_btn.one('click', function() {
fl_box.close();
if (callback) {
callback.apply(fl_box);
}
});
return fl_box;
}
function SK_confirm($title, $contents, callback)
{
if (!callback &&
typeof $contents == 'function' &&
$contents.constructor != Array) {
callback = $contents;
}
if (!$contents || $contents == callback) {
$contents = $title;
$title = SK_Language.text('%interface.confirmation_title');
}
var $ok_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.ok'));
var $cancel_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.cancel'));
var fl_box = new SK_FloatBox({
$title: $title,
$contents: $contents,
$controls: jQuery($ok_btn)
.add('<span> </span>')
.add($cancel_btn)
});
$ok_btn.one('click', function() {
fl_box.close();
if (callback) {
callback.apply(fl_box);
}
});
$cancel_btn.one('click', function() {
fl_box.close();
});
return fl_box;
}
function SK_BlockHandler(block_node)
{
this.$block = jQuery(block_node);
this.$block_cap =
jQuery('.block_cap:eq(0)', this.$block);
this.$title =
jQuery('.block_cap_title:eq(0)', this.$block_cap);
this.$body =
jQuery('.block_body:eq(0)', this.$block);
this.$expand_btn =
jQuery('.block_expand:eq(0), .block_collapse:eq(0)', this.$block_cap);
this.events = {
click: [],
expand: [],
collapse: []
}
var handler = this;
this.$block_cap
.click(function() {
if (handler.$expand_btn.hasClass('block_expand')) {
handler.expand();
}
else if (handler.$expand_btn.hasClass('block_collapse')) {
handler.collapse();
}
return false;
});
}
SK_BlockHandler.prototype = {
expand: function(trigger_events)
{
if (trigger_events === undefined) {
trigger_events = true;
}
if (!trigger_events || (
this.trigger('expand') !== false
&& this.trigger('click') !== false)
) {
this.$expand_btn.attr('class', 'block_collapse');
this.$body.slideDown('fast');
}
return this;
},
collapse: function(trigger_events)
{
if (trigger_events === undefined) {
trigger_events = true;
}
if (!trigger_events || (
this.trigger('collapse') !== false
&& this.trigger('click') !== false)
) {
this.$expand_btn.attr('class', 'block_expand');
this.$body.slideUp('fast');
}
return this;
},
show: function(speed, callback) {
this.$block.show(speed, callback);
},
hide: function(speed, callback) {
this.$block.hide(speed, callback);
},
bind: function(type, arg1, arg2)
{
if (this.events[type] == undefined) {
throw 'block error: unknown event type "'+type+'"';
}
if (!arg2) {
this.events[type].push([arg1]);
}
else {
this.events[type].push([arg1, arg2]);
}
},
trigger: function(type)
{
if (this.events[type] == undefined) {
throw 'block error: unknown event type "'+type+'"';
}
for (var i = 0, item; item = this.events[type][i]; i++)
{
if (item.length == 1) {
if (item[0].apply(this) === false) {
return false;
}
}
else if (item[1].call(this, item[0]) === false) {
return false;
}
}
return true;
},
clone: function(clone_e)
{
var $clone = this.$block.clone();
var node = $clone.get(0);
node.sk_block_handler = new SK_BlockHandler(node);
if (clone_e) {
node.sk_block_handler.events = this.events;
}
return node.sk_block_handler;
},
append: function(content) {
return this.$body.append(content);
return this;
},
appendTo: function(content) {
this.$block.appendTo(content);
return this;
},
empty: function() {
this.$body.empty();
return this;
},
children: function(expr) {
return this.$body.children(expr).not('.block_body_corner');
},
find: function(expr) {
return this.$body.find(expr).not('.block_body_corner');
},
removeAttr: function(name) {
this.$block.removeAttr(name);
return this;
},
addClass: function(cls) {
this.$block.addClass(cls);
return this;
},
removeClass: function(cls) {
this.$block.removeClass(cls);
return this;
}
}
jQuery(function() {
jQuery('.block_expand, .block_collapse')
.each(function() {
var block_node = this.parentNode.parentNode.parentNode.parentNode;
if (jQuery(block_node).hasClass('block')) {
block_node.sk_block_handler = new SK_BlockHandler(block_node);
}
});
});
SK_Language = {
data: {},
text: function(lang_addr, var_list)
{
if ( SK_Language.data[lang_addr] === undefined ) {
throw new SK_Exception('language section ['+lang_addr+'] not found');
}
var text = SK_Language.data[lang_addr];
if (var_list) {
for ( key in var_list ) {
text = text.replace('{$'+key+'}', var_list[key]);
}
}
return text;
}
}
function nl2br(str) {
return (str + '').replace(/([^>]?)\n/g, '$1<br />\n');
}
function SK_SignIn() {
return window.sk_component_sign_in.showBox();
}
function SK_openIM(opponent_id, is_esd)
{
if (is_esd)
is_esd_session = '&is_esd_session='+is_esd;
else
is_esd_session = '';
return window.open(
URL_MEMBER+'im.php?opponent_id='+opponent_id+is_esd_session,
'im_with_'+opponent_id,
'width='+SK_openIM.width+','+
'height='+SK_openIM.height+','+
'resizable=yes, location=no, scrollbars=no, status=no'
);
}
SK_openIM.width = 445;
SK_openIM.height = 460;
function SK_profileNote( event_id, opponent_id)
{
return window.open(
URL_MEMBER+'profile_note.php?event_id='+event_id+'&opponent_id='+opponent_id,
'note_'+opponent_id,
'width='+SK_profileNote.width+','+
'height='+SK_profileNote.height+','+
'resizable=yes, location=no, scrollbars=no, status=no'
);
}
SK_profileNote.width = 325;
SK_profileNote.height = 425;
SK_EventManager = {
events: {},
bind: function(event, callback)
{
if ( typeof this.events[event] == 'undefined' || this.events[event] === null)
{
this.events[event] = [];
}
this.events[event].push(callback);
},
trigger: function(event, eventObject)
{
if (typeof this.events[event] != 'undefined' && this.events[event] !== null)
{
for (var i = 0; i < this.events[event].length; i++)
{
if (typeof this.events[event][i] == 'function')
{
if (this.events[event][i](eventObject) === false)
{
return;
}
}
}
}
}
};
SK_SetFieldInvitation = function(id, label)
{
var $node = $('#' + id);
$node.addClass('input_invitation').val(label);
$node.focus(function() {
var v = $node.val();
$node.removeClass('input_invitation');
if ( v == label )
{
$node.val('');
}
}).blur(function() {
var v = $node.val();
if ( !v )
{
$node.addClass('input_invitation').val(label);
}
});
$($node.get(0).form).submit(function(){
if ( $node.val() != label )
{
$node.removeClass('input_invitation');
}
});
}
<div class="floatbox_container" style="overflow: visible; width: 320px; opacity: 0.1; display: block; top: 274px; left: 736px;">
<div class="block_cap floatbox_header"><div class="block_cap_r"><div class="block_cap_c clearfix"><h3 class="block_cap_title"><b>Şifremi unuttum!</b></h3><a class="close_btn" href="#"></a></div></div></div> <div class="floatbox_body">
<div class="fblock_body block_body">
<div class="fblock_body_r block_body_r">
<div class="fblock_body_c block_body_c">
<div class="block_info">Şifremi yenile</div><form id="form_3" method="post" onsubmit="return false;">
<label>E-posta</label>: <input id="form_3-email" name="email" type="text" maxlength="255">
<div id="form_3-email-container"></div>
<div class="controls center float_left">
<input id="form_3-send-button" type="submit" value="Gönder"> </div>
<div class="clr"></div>
</form></div>
</div>
</div>
</div>
<div class="floatbox_bottom">
<div class="block_bottom">
<div class="block_bottom_r">
<div class="block_bottom_c">
</div>
</div>
</div>
</div>
<div class="fblock_bottom">
<div class="fblock_bottom_r">
<div class="fblock_bottom_c"></div>
</div>
</div>
</div>
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.
In creating a table cells with very cool options I need to take two steps. First I create the table cell as a DOM object in javascript with all the 'normal' functionality, like is it a checkbox, a select, an input, a link, etc.
Then I need to put the table on the page to do the next step, which I consider advanced functionality like jqueryui's autocomplete and date select. It is awesome to have these drop downs for the user.
I do have this working, however, I do need to make two calls. The first to createTableCell, then I render, then I need to make another call to postRenderTableFunctions to get the autocomplete functionality working. So the question is, why the second call, what is it about jqueryui that will not work on the first call. You can see the commented section under input creation where I tried to get the autocomplete working.
function createTableCell(name, td_def)
{
var cell=document.createElement('td');
if(td_def['type'] == 'date')
{
var element = document.createElement('input');
element.name = name;
element.id = name;
cell.appendChild(element);
$('#' + element.id).datepicker(
{
dateFormat: 'yy-mm-dd',
onSelect: function ()
{
$(this).focus();
},
onClose: function (dateText, inst)
{
$(this).select();
}
});
}
else if(td_def['type'] == 'checkbox')
{
element = document.createElement('input');
element.type = 'checkbox';
element.name = name;
element.id = name;
/*if(this.tdo[r][td_def['db_field']]['data'] == 1)
{
element.checked = true;
}*/
cell.appendChild(element);
}
else if (td_def['type'] == 'select')
{
element = document.createElement('select');
element.name = name;
element.id = name;
var option = document.createElement('option');
option.value = 'NULL';
option.appendChild(document.createTextNode("Select..."));
element.appendChild(option);
for (var j in td_def['select_names'])
{
option = document.createElement('option');
option.value = td_def['select_values'][j];
option.appendChild(document.createTextNode(td_def['select_names'][j]));
element.appendChild(option);
}
cell.appendChild(element);
}
else if (td_def['type'] == 'tree_select')
{
element = document.createElement('select');
element.id = name;
element.name = name;
var option = document.createElement('option');
option.value = 'NULL';
option.appendChild(document.createTextNode("Select..."));
element.appendChild(option);
var level = 0;
//console.log(td_def['select_array']);
this.addNestedSelectOptions(element, td_def['select_array'], level);
if (typeof td_def['properties'] !== 'undefined')
{
for (var index in td_def['properties'])
{
eval('element.' + index + '= ' + td_def['properties'][index] + ';');
}
}
cell.appendChild(element);
}
else if (td_def['type'] == 'input')
{
element = document.createElement('input');
element.type = 'text';
element.id = name;
element.name = name;
cell.appendChild(element);
/*
if(typeof td_def['autoComplete'] != 'undefined')
{
console.log('attempting Autocomplete');
$( "#" + name ).autocomplete({
source: function( request, response )
{
$.ajax(
{
url: td_def['autoComplete']['url'],
type: 'GET',
async: true,
data:
{
ajax_request: td_def['autoComplete']['ajax_request'],
featureClass: "P",
style: "full",
maxRows: 12,
search_terms: request.term
},
success: function( data )
{
console.log(data);
parsed_autocomplete_data = parseJSONdata(data);
response( parsed_autocomplete_data);
}
});
},
search: function()
{
// custom minLength
var term = this.value;
//console.log(term);
if(typeof td_def['minLength'] != 'undefined')
{
var minL = td_def['minLength'];
}
else
{
var minL = 1;
}
if ( term.length < minL )
{
return false;
}
},
focus: function()
{
// prevent value inserted on focus
return false;
},
open: function(event, ui)
{
var dialog = $(this).closest('.ui-dialog');
if(dialog.length > 0){
$('.ui-autocomplete.ui-front').zIndex(dialog.zIndex()+1);
}
},
select: function( event, ui )
{
selected_autocomplete_index = $.inArray(ui.item.value, parsed_autocomplete_data);
}
});
}
*/
}
else if (td_def['type'] == 'textarea')
{
element = document.createElement('TEXTAREA');
element.id = name;
element.name = name;
cell.appendChild(element);
}
else if (td_def['type'] == 'td')
{
cell.innerHTML = 'TBD';
cell.name = name;
cell.id = name;
}
else
{
alert(td_def['type'] + ' have not coded that.....');
}
return cell;
function addNestedSelectOptions(element, category_array, level)
{
for (var key in category_array)
{
option = document.createElement('option');
option.value = key;
name = category_array[key]['name'];
for(i=0;i<level;i++)
{
name = "\u00A0" + name;
name = "\u00A0" + name;
}
option.appendChild(document.createTextNode(name));
element.appendChild(option);
if(!$.isEmptyObject(category_array[key]['children']))
{
addNestedSelectOptions(element, category_array[key]['children'], level+1);
}
}
}
}
//this function needs to be called separately.
function postRenderTableFunctions(table_div_id, table_def)
{
//extra jquery functionality -- needs to go after stuff is rendered
for(var i=0;i<table_def.length;i++)
{
if(typeof table_def[i]['autoComplete'] != 'undefined')
{
var id = table_div_id + '_' + table_def[i]['db_field'];
console.log(id);
//is the auto complete open?
/*$("#" + id ).bind('autocompleteopen', function(event, ui)
{
$(this).data('is_open',true);
});
$("#" + id ).bind('autocompleteclose', function(event, ui)
{
$(this).data('is_open',false);
});*/
/*$( "#" + id ).bind( "keydown", function( event )
{
//what is this for ?
if ( event.keyCode === $.ui.keyCode.TAB && $(this).data('is_open') )
{
event.preventDefault();
}
if ( event.keyCode === $.ui.keyCode.ENTER && !$(this).data('is_open'))
{
//do what?
}
});*/
var i2 = i;
var me = table_def;
$( "#" + id ).autocomplete({
source: function( request, response )
{
$.ajax(
{
url: me[i2]['autoComplete']['url'],
type: 'GET',
async: true,
data:
{
ajax_request: me[i2]['autoComplete']['ajax_request'],
featureClass: "P",
style: "full",
maxRows: 12,
search_terms: request.term
},
success: function( data )
{
console.log(data);
parsed_autocomplete_data = parseJSONdata(data);
response( parsed_autocomplete_data);
}
});
},
search: function()
{
// custom minLength
var term = this.value;
//console.log(term);
if(typeof table_def[i2]['minLength'] != 'undefined')
{
var minL = table_def[i2]['minLength'];
}
else
{
var minL = 1;
}
if ( term.length < minL )
{
return false;
}
},
focus: function()
{
// prevent value inserted on focus
return false;
},
open: function(event, ui)
{
var dialog = $(this).closest('.ui-dialog');
if(dialog.length > 0){
$('.ui-autocomplete.ui-front').zIndex(dialog.zIndex()+1);
}
},
select: function( event, ui )
{
selected_autocomplete_index = $.inArray(ui.item.value, parsed_autocomplete_data);
}
});
}
}
}
My original comment to your question -
I suspect i may work if you replace
$( "#" + name ).autocomplete({
with
$(element).autocomplete({
though I don't currently have means to test it.
My response -
Basically using $("#name") looks for an element with the ID name in the DOM. When you are running your code element has not been added to the DOM yet so the autocomplete cannot be attached to to your element.
Surrounding element with $() converts it to a jQuery variable which you can attach the autocomplete to before it is added to the DOM.
So here is my autocomplete functionality:
var selected;
var itemAdded = false;
$('.js-main-search').autocomplete({
minLength: 3,
source: function(request, response) {
$.getJSON('/dashboard/searchDocumentsAndCompanies.do',
{ q: request.term},
function(data) {
if(data.length == 0){
data = [
{name: 'No matches found', resultType: 'COMPANY', noResults: true},
{name: 'No matches found', resultType: 'BRANCHES', noResults: true},
];
}
data.unshift({name: 'Search from documents »', reqQuery: request.term, docSearch:true});
response(data);
});
},
select: function( event, ui ) {
event.preventDefault();
selected = true;
if(ui.item.docSearch && !itemAdded){
$(".textbox.ui-front li:eq(1)").before('<li class="search-category ui-menu-item">Documents</li>');
itemAdded = true;
}
}
});
$('.js-main-search').data("uiAutocomplete").close = function(event) {
if (!selected){
$('.js-main-search').data("uiAutocomplete").close.apply( this, arguments );
}
selected = false;
};
$('.js-main-search').data('uiAutocomplete')._renderItem = function( ul, item ) {
itemAdded = false;
item.value = item.name;
var $el = $( "<li>" ).append(item.value);
if(item.docSearch){
$el.addClass( "search-documents-btn" );
$el.one('click', function (e) {
e.preventDefault();
console.log(ul.children());
});
}
if(!item.noResults && !item.docSearch){
$el.append('<div class="meta">Documents | Company page</div>');
}
$el.appendTo( ul );
return $el;
};
$('.js-main-search').data('uiAutocomplete')._renderMenu = function(ul, items) {
var companiesResults = true;
var branchesResults = true;
var that = this,currentCategory = '';
$.each(items, function(index, item) {
var li;
if (item.resultType != currentCategory && !item.docSearch) {
var categoryTitle = '';
if(item.resultType == 'COMPANY'){
categoryTitle = 'Companies';
companiesResults = false;
} else{
categoryTitle = 'Branches'
branchesResults = false;
}
ul.append('<li class="search-category">'+categoryTitle+'</li>');
currentCategory = item.resultType;
}
li = that._renderItemData(ul, item);
if (item.resultType) {
item.value = item.name;
li.attr('aria-label', item.resultType + ' : '+ item.value);
}
});
if(companiesResults && branchesResults){
ul.append('<li class="search-show-more-btn">Show more</li>');
}
};
When I am starting to enter search keyword sometimes it gives me the following error in console: "Too much recursion", but I don't understand why.
Any suggestions are welcome.
Usually when you get a stack overflow error, it is because you have a recursion for which no exit condition exist or is triggered. Looking at your code, here's the function that causes the problem.
$('.js-main-search').data("uiAutocomplete").close = function (event) {
if (!selected) {
$('.js-main-search').data("uiAutocomplete").close.apply(this, arguments);
}
selected = false;
};
I guess the selected = false; should be inside the if statement before the recursive call like so:
$('.js-main-search').data("uiAutocomplete").close = function (event) {
if (!selected) {
selected = false;
$('.js-main-search').data("uiAutocomplete").close.apply(this, arguments);
}
};
I am using infinite scroll to load posts and tried to integrate a custom like button for every single posts that needs a small jquery script to work. My problem is I added this Jquery directly after the sucess in ajax load posts. But when I load eg the 3. page my jquery script executes twice and on the posts of the 2nd page the lke buttons are not working correctly. How can I handle this? If I dont execute the code after the ajax request and only call this jquery code globally the like buttons do not work in the new loaded posts of the ajax infinite scroll. Maybe I need to stop the sript of before when eg loadin 3. page through the ajax infinite scroll but how? This is my code:
function load_more_posts(selector){
var url = $(selector).attr('href');
var data;
loading = true;
$.ajax({
url: url,
data: data,
success: function( data ) {
var $items = $( '.loading-content .item', data );
$new_anchor = $( selector, data );
$items.addClass('hidden');
if ( $('#cooked-plugin-page .result-section.masonry-layout .loading-content').length ){
$( '.loading-content').isotope( 'insert', $items );
} else {
$( '.loading-content').append($items);
setTimeout(function() {
$items.removeClass('hidden');
}, 200);
}
if($new_anchor.length) {
$(selector).attr('href', $new_anchor.attr('href'));
} else {
$(selector).remove();
}
loading = false;
$('.like-btn').each(function() {
var $button = $(this),
$icon = $button.find('> i'),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id');
cookied = $button.attr('data-cookied');
userLiked = $button.attr('data-userliked');
if ( cookied == 1 && typeof likedRecipes !== 'undefined' && likedRecipes.split(',').indexOf(recipeID) > -1 || userLiked == 1 ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
}
});
$('#cooked-plugin-page .like-btn').on('click', function() {
var $button = $(this),
$icon = $button.find('> i'),
$count = $button.find('.like-count'),
count = parseInt($count.text()),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id'),
cookied = $button.attr('data-cookied'),
likeURL = $button.attr('href'),
likeAction;
if ( $icon.hasClass('fa-heart-o') ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
count++;
if (cookied == 1){
if ( typeof likedRecipes === 'undefined' ) {
likedRecipes = recipeID;
} else {
likedRecipes = likedRecipes + ',' + recipeID;
}
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
}
likeAction = 'like';
} else {
$icon.removeClass('fa-heart').addClass('fa-heart-o');
count--;
if (cookied == 1){
if ( typeof likedRecipes === 'undefied' ) {
return false;
}
}
if (cookied == 1){
var likedSplit = likedRecipes.split(','),
recipeIdx = likedSplit.indexOf(recipeID);
if ( recipeIdx > -1 ) {
likedSplit.splice( recipeIdx, 1 );
likedRecipes = likedSplit.join(',');
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
likeAction = 'dislike';
}
} else {
likeAction = 'dislike';
}
}
$.ajax({
'url' : likeURL,
'data': {
'action' : 'cp_like',
'likeAction': likeAction
},
success: function(data) {
$count.text(data);
}
});
return false;
});
$('#cooked-plugin-page .tab-links a').on('click', function() {
var tab = $(this).attr('href');
if ( !$(this).is('.current') ){
$(this).addClass('current').siblings('.current').removeClass('current');
$('#cooked-plugin-page.fullscreen .tab').removeClass('current');
$(tab).addClass('current');
$win.scrollTop(0);
}
return false;
});
if($('.rating-holder').length) {
$('.rating-holder .rate')
.on('mouseenter', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
$parent.addClass('rate-' + (my_index + 1));
})
.on('mouseleave', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
if(rated !== undefined) {
$parent.addClass('rate-' + rated);
}
})
.on('click', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
$('.rating-real-value').val(my_index + 1);
$parent.attr('data-rated', my_index + 1);
$parent.addClass('rate-' + (my_index + 1));
});
}
setTimeout(function() {
masonry();
}, 500);
}
});
}
There's a great plugin for scrolling. He has methods such as bund, unbind, destroy and e.t.c.:
https://github.com/infinite-scroll/infinite-scroll#methods