I'm trying to apply this tutorial on my website
Getting Loopy - Ajax Powered Loops with jQuery and WordPress
DEMO
I applied everything and I'm getting this error from Chrome console
Uncaught TypeError: undefined is not a function
This my code:
// ajaxLoop.js
jQuery(function($){
var page = 1;
var loading = true;
var $window = $(window);
var $content = $("#articles-wrapper");
var load_posts = function(){
$.ajax({
type : "GET",
data : {numPosts : 5, pageNumber: page},
dataType : "html",
url : "http://www.dzlng.com/demo/wp-content/themes/dzlng/loopHandler.php",
beforeSend : function(){
if(page != 1){
/* $content.append('<div id="temp_load" style="text-align:center">\
loading....\
</div>');*/
}
},
success : function(html){
$data = $(html);
if($data.length){
//$data.hide();
var newItems = $(html).appendTo($("#articles-wrapper"));
imagesLoaded('#articles-wrapper', function() {
$("#articles-wrapper").isotope('appended', newItems );
});
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$window.scroll(function() {
var content_offset = $content.offset();
//console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
});
And:
<?php
//loopHandler.php
// Our include
define('WP_USE_THEMES', false);
require_once('../../../wp-load.php');
// Our variables
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page
));
// our loop
if (have_posts()) {
while (have_posts()){
the_post();
get_template_part( 'content', 'item' );
}
}
wp_reset_query();
?>
I tried few stuff but it's not working.
Related
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
I am sent many dynamic post ids from a page and a php server side page(server.php) make a query with those id to find out newly added data in mysql.
If it not found any newly added data in mysql, it's return a undefined value. So as per my script, It's append a undefined one after one at a time interval.
So how can I check, if php query cannot found anything in sql then exit and not return anything?
I tried this in my php if(mysqli_num_rows($res)) { //do something } but it's also display undefined.
my javascript:
var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
});
}
function waitForRep(){
$.ajax({
type: "GET",
url: "server.php",
cache: false,
data: {CID : CID},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(waitForRep, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForRep, 15000); }
});
}
$(document).ready(function(){
waitForRep();
});
server.php
while (true) {
if($_REQUEST['CID']){ //cid got all dynamic post id as: 1,2,3,4 etc.
foreach($_REQUEST['CID'] as $key => $value){
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$data = array();
while($rows = mysqli_fetch_assoc($res)){
$data[]=$rows;
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
$data['username'] = $rows['username'];
$data['description'] = $rows['description'];
$data['date'] = $rows['date'];
//etc. all
$id = $rows['id'];
$qazi_id = $rows['qazi_id'];
$username = $rows['username'];
$description = $rows['description'];
//etc. all
} //foreach close
} //foreach close
if ($description=="") {$detail .= '';}
else {$detail .=''.$description.'';}
$data['detail'] = $detail;
// do others something more
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} //request close
sleep(5);
} //while close
I tried this in my php if(mysqli_num_rows($res)) { //do something } but it's also display undefined.
I guess that should be because you are calling this php code every 15000 ms via ajax with a setTimeout.
So instead stopping it there you can just ignore it with your js code in addrep() function.
function addrep(type, msg) {
CID.forEach(function(id) {
if (msg.id !== undefined && msg.detail !== undefined) { // <--check undefined here
$("#newreply" + id).append("<div class='" + type + "" + msg.id + "'>"+
"<ul><div class='cdomment_text'>" + msg.detail +
"</ul></div>");
}
});
}
Or other option is to make use of clearTimeout() when you get undefined.
var timer; // declare the timer here
var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i) {
CID[i] = $(this).data('post-id');
});
function addrep(type, msg) {
CID.forEach(function(id) {
if(msg.id === undefined || msg.details === undefined){
clearTimeout(timer); // cleartimeout timer
}else{
$("#newreply" + id).append("<div class='" + type + "" + msg.id + "'><ul><div class='cdomment_text'>" + msg.detail + "</ul></div>");
}
});
}
function waitForRep() {
$.ajax({
type: "GET",
url: "server.php",
cache: false,
data: {
CID: CID
},
timeout: 15000,
success: function(data) {
addrep("postreply", data);
timer = setTimeout(waitForRep, 15000); // assign the settimeout to timer
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
setTimeout(waitForRep, 15000);
}
});
}
$(document).ready(function() {
waitForRep();
});
I am doing an AJAX call from a function. Everything works fine until the AJAX call(I tried console.log before the AJAX call that was executed). It calls a controller's index function from there it returns the JSON object
in view:
$.ajax({
type: "POST",
url: "<?php echo $this->Html->url('/proposals');?>",
data: form,
dataType: "json",
success: function(data){
//alert(data.id+'--'+data.msg);
console.log("test");
if(data.msg == 'success'){
var valueRemaining= $('#RemainingFunding').val() ;
if (valueRemaining <= 0 ) {
alert ('No Funds Remaining');
return false;
}
var valueSubmitted = $('#subtotal'+state).text();
var valueSubmitted = parseInt(valueSubmitted);
if (valueSubmitted != null || valueSubmitted != '') {
//var substract = valueRemaining - valueSubmitted;
//$('#RemainingFunding').val(substract);
}
//console.log( 'value of subtotao f = ' + subflt );
$('#ProposalId').val(data.id); //ajx_submit
$('#sum').val(data.propsum);
$('#ajx_submit').val(parseInt(tot_ajxsub)+1);
$("input:radio[id=ProposalAnotherLocationY]").prop('checked', false);
$('#fld_subtotal').val('0');
pastSubtotals += flttot;
console.log("test");
tableState=0;
//console.log( 'value of pastSubtotal = ' + pastSubtotals);
//$('#RemainingFunding'). val(intamtval);
}else if(data.msg == 'error'){
alert('Proposal budget can not be blank!!');
return false;
}else {
alert('no match');
}
return false;
//$("#form")[0].reset();
//Unterminated String constant fixed
}
});
Controller:
if ($this - > request - > isAjax()) {
$Proposalsum = $this - > DftsProposalbudget - > find('all', array('fields' => array('SUM(DftsProposalbudget.cy1) as cy1', 'SUM(DftsProposalbudget.cy2) as cy2', 'SUM(DftsProposalbudget.cy3) as cy3 ', 'SUM(DftsProposalbudget.cy4) as cy4 ', 'SUM(DftsProposalbudget.cy5) as cy5', 'SUM(DftsProposalbudget.cy6) as cy6', 'SUM(DftsProposalbudget.cy7) as cy7', 'SUM(DftsProposalbudget.cy8) as cy8', 'SUM(DftsProposalbudget.cy9) as cy9', 'SUM(DftsProposalbudget.cy10) as cy10'), 'conditions' => array('DftsProposalbudget.proposal_id' => $LastID, 'DftsProposalbudget.user_id' => $UID), 'group' => 'DftsProposalbudget.proposal_id'));
$sum = 0;
echo '<pre>'.print_r($Proposalsum, true).
"</pre>";
if (!empty($Proposalsum)) {
foreach($Proposalsum[0][0] as $key => $value) {
//echo $sum += $value['0']['cy1'];
$sum += $value;
}
}
echo json_encode(array('msg' => 'success', 'id' => $LastID, 'propsum' => $sum));
exit(0); //json_encode('msg' => 'success', 'id' => '1');
In the network I get this message:
But it is not printing or working for anything that is in the block success.
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
I'm using Isotope with AJAX to pull in some posts in WordPress, pretty much everything is there, except for the default Isotope animation runs when I AJAX in content, which looks a bit weird. I still wanted it to animate when filtered though.
So I thought I could just use add/removeClass within my AJAX function to turn it off/on when needed, but if I do the animation never runs.
Any ideas where I'm going wrong here?
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
if( $('body').hasClass('home') ) {
var loopHandler = '/inc/loop-handler.php';
} else {
var loopHandler = '/inc/loop-handler-archive.php';
}
var load_posts = function(){
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page},
dataType : "html",
url : templateDir+loopHandler,
beforeSend : function(){
if(page != 1){
$('.loader').append('<div id="temp_load" style="text-align:center; z-index:9999;">\
<img src="'+templateDir+'/img/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
var itemHeight = $('.item').height();
var height = $content.height()+itemHeight*2;
$content.append($data);
$content.css('min-height', height);
$data.hide();
// should stop the animation
$('.isotope').addClass('no-transition');
$content.isotope('destroy');
$content.imagesLoaded( function(){
$content.isotope({
// options
layoutMode: 'fitRows',
itemSelector : '.item'
});
});
$data.fadeIn(700, function(){
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// should start up the animation again
$('.isotope').removeClass('no-transition');
$content.css('min-height', '0');
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() +
$content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
If you need any of the HTML/PHP I'm happy to post it up. Also, here's the dev site if you want to check it out.
I don't know Isotope and I have not tested if it works. But I have refactor your code with annotations to help you better understand the problem.
I think it comes from how you call removeClass and addClass successively, the two instantly cancel.
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
var loopHandler = '/inc/loop-handler.php';
var isotopeController = {
append: function($data) {
// Add AJAX data
var itemHeight = $('.item').height();
var height = $content.height() + itemHeight * 2;
$content.append($data);
$content.css('min-height', height);
// Stop
isotopeController.stop($data);
// Restart
$content.imagesLoaded(function() {
// When images loaded !
isotopeController.start($data);
});
},
start: function($data) {
// Start isotope
$content.isotope({
layoutMode: 'fitRows',
itemSelector: '.item'
});
// Show data
$data.fadeIn(700, function() {
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// Start the animation
$content.removeClass('no-transition');
$content.css('min-height', '0');
},
stop: function($data) {
// Hide data
$data.hide();
// Stop the animation
$content.addClass('no-transition');
// Stop isotope
$content.isotope('destroy');
},
loadPosts: function() {
$.ajax({
type: "GET",
data: {
numPosts: 1,
pageNumber: page
},
dataType: "html",
url: templateDir + loopHandler,
beforeSend: function() {
if (page != 1) {
$('.loader').append('' +
'<div id="temp_load" style="text-align:center; z-index:9999;">' +
'<img src="' + templateDir + '/img/ajax-loader.gif" />' +
'</div>'
);
}
},
success: function(data) {
var $data = $(data);
if ($data.length) {
isotopeController.append($data);
} else {
$("#temp_load").remove();
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
};
$window.scroll(function() {
var content_offset = $content.offset();
if (!loading && ($window.scrollTop() + $window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
isotopeController.loadPosts();
}
});
// On load
$(function() {
if (!$('body').hasClass('home')) {
loopHandler = '/inc/loop-handler-archive.php';
}
isotopeController.loadPosts();
});