JQuery Ajax, how do I not repeat my code? - ajax

I have this code:
I want it to do something by default, basically when you view the page, it makes an ajax request and displays all data.
but when you click a link it displays specific data.
But how do I do this without repeating code.
example:
// when click on the link
$('a').click( function(){
$.getJSON('file.ext', function( data ){
//same code
});
});
// when the page is loaded
$.getJSON('file.ext', function( data ){
//same code
});

Just wrap your .getJSON() call in a function that is called from both locations.
// Define function
function getData() {
$.getJSON('file.ext', function( data ){ ... });
}
// Call on click
$('a').click(function () {
getData();
});
// Call on load
getData();

Just create a function, write once, use many.
$('a').click( function(){
$.getJSON('file.ext', function( data ){
customFunction();
});
});
// when the page is loaded
$.getJSON('file.ext', function( data ){
customFunction();
});
customFunction = function () {
//code
};

Related

Error: “cannot call methods on masonry prior to initialization'” when combining masonry grid with search and filter WordPress plugin

I am trying to use the Masonry grid with the WordPress plugin Search and Filter Pro using ajax to load the posts upon filtering. I am getting the error:
Error: “cannot call methods on masonry prior to initialization; attempted to call ‘reloadItems’”
Both Masonry and Search and Filter address this issue.
Masonry recommends using this code:
$grid.imagesLoaded( function() {
// init Masonry
$grid.masonry({
// options...
});
// Masonry has been initialized, okay to call methods
$grid.append( $items )
.masonry( 'appended', $items );
});
Search and Filter recommends using this code:
//detects when the ajax request has finished and the content has been updated
// - add scripts that apply to your results here
$(document).on("sf:ajaxfinish", ".searchandfilter", function(){
console.log("ajax complete");
//so load your lightbox or JS scripts here again
});
So, I've incorporated this and my final code is:
(function ($) {
var $container = $('.grid');
$container.imagesLoaded(function () {
// INITIALIZE MASONRY
$container.masonry({
itemSelector: '.entry',
columnWidth: '.entry',
gutter: 40,
});
// MASONRY HAS BEEN INITIALIZED, OKAY TO CALL METHODS
$(document).on("sf:ajaxfinish", ".searchandfilter", function () {
$container.masonry('reloadItems');
});
});
}(jQuery));
but nothing changes. I get the same error.
This is what I used.
jQuery(document).ready(function($) {
function loadMasonry(){
//$container will always be a new copy
var $container = $('.featured-grid-thirds');
//running images loaded again after page load / ajax event
$container.imagesLoaded(function () {
// INITIALIZE MASONRY
$container.masonry({
itemSelector: '.featured-grid-item',
columnWidth: '.featured-grid-sizer',
gutter: '.gutter-sizer',
percentPosition: true
});
// Masonry has been initialized, okay to call methods
// reload masonry
$container.masonry('reloadItems');
});
}
//Call on page load etc...
loadMasonry();
//then also call it after ajax event
$(document).on("sf:ajaxfinish", ".searchandfilter", function () {
console.log("ajax complete");
loadMasonry();
});
});

Packery not arranging additional divs when loaded via AJAX

I am using packery to arrange blog posts in a masonry format. This works fine for posts that are initially displayed on the page but when I load new posts - when the pagination links are clicked - via AJAX the posts just get added to the container but do no 'repack' or re-arrange in a masonry format.
I am using WordPress and using my own AJAX call, see code below:
// For jQuery noConflict
(function($) {
$(document).ready(function() {
// Find out the page number
var pageNumber;
$('.custom-pagination a.page-numbers').click(function() {
pageNumber = $(this).html();
});
// AJAX call to load more posts when pagination links are clicked
$(document).on( 'click', '.custom-pagination a.page-numbers', function( event ) {
event.preventDefault();
page = pageNumber;
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
success: function( html ) {
var $container = $('#all-posts').packery();
$container.append( html );
$container.packery( 'appended', html );
}
});
});
});
})(jQuery);
// End jQuery noConflict
Can anyone point me in the right direction on how to call packery again to re-arrange my posts in a masonry format after they are loaded via AJAX?
Thanks.
I had the same issue, and took care of it server-side (web2py/python), in accordance with the instructions here:
# this function is called via ajax
def function_that_loads_the_new_content():
...
new_divs = #generate new content
new_divs_as_string = ''.join([str(x) for x in new_divs])
# this script runs when the new content is appended to the container
update_results = \
"var $items = $('%s');$pack.append($items).packery( 'appended', $items );" \
% new_divs_as_string
return update_results
The idea is to use packery's appending functionality after the new elements have been added to the container element. The above script is essentially equivalent to this template offered in the packery page:
$('.append-button').on( 'click', function() {
// create new item elements
var $items = $('<div class="grid-item">...</div>');
// append items to grid
$grid.append( $items )
// add and lay out newly appended items
.packery( 'appended', $items );
});

hash in url to deep linking with ajax

I've this code to load content in a div #target with some animation. Works fine but i don't know how implement code to change link and url with #hash!
How can I do this?
the code:
$(document).ready(function(){
$("#target").addClass('hide');
$('.ajaxtrigger').click(function() {
var pagina = $(this).attr('href');
if ($('#target').is(':visible')) {
}
$("#target").removeClass('animated show page fadeInRightBig').load(pagina,
function() {
$("#target").delay(10).transition({ opacity: 1 })
.addClass('animated show page fadeInRightBig');
}
);
return false;
});
});
Try to use any javascript router. For example, router.js.
Modify you code like this(I didn't check if this code work, but I think idea should be clear):
$(document).ready(function(){
var router = new Router();
//Define route for your link
router.route('/loadpath/:href', function(href) {
console.log(href);
if ($('#target').is(':visible')) {
$("#target").removeClass('animated show page fadeInRightBig').load(href,
function() {
$("#target").delay(10).transition({ opacity: 1 })
.addClass('animated show page fadeInRightBig');
}
);
}
});
router.route('', function(){ console.log("default route")});
$("#target").addClass('hide');
// Instead of loading content in click handler,
// we just go to the url from href attribute with our custom prefix ('/loadpath/').
// Router will do rest of job for us. It will trigger an event when url hash is
// changes and will call our handler, that will load contents
// from appropriate url.
$('.ajaxtrigger').click(function() {
router.navigate('/loadpath/' + $(this).attr('href'));
return false;
});
});

Live jQuery events not firing for dynamic element

Why are none of the live (or dead) events I bind to a dynamic element firing?
(function ($) {
$.fn.myPlugin = function () {
var $filterBox = $("<input type='text'>").live("click", function () {
alert("Clicked");
});
this.before($filterBox); // insert into DOM before current element
return this; // keep chain
};
})(jQuery);
I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?
Edit:
The following does not work either:
var $filterBox = $("<input type='text'>").bind("click", function () {
alert("Clicked");
});
.live() works off a selector (since it checks the target against the selector at the time the event happens), you can't attach it directly to an element...you should just use .click() in these cases:
(function ($) {
$.fn.myPlugin = function () {
var $filterBox = $("<input type='text'>").click(function () {
alert("Clicked");
});
this.before($filterBox); // insert into DOM before current element
return this; // keep chain
};
})(jQuery);
You can try it out here, or a bit shorter with .insertBefore():
(function ($) {
$.fn.myPlugin = function () {
$("<input type='text'>").click(function () {
alert("Clicked");
}).insertBefore(this);
return this;
};
})(jQuery);
You can test it here.
The live method works with selectors, not detached elements.
You can handle the normal (non-live) click event, and it should work fine.
Why not just bind it? http://jsfiddle.net/9WvpA/
Can it be just because "<input type='text'>" is not a valid HTML? You have not closed your tag. However, I am not sure whether jQuery is unable to close it for you.
Solved by not using global variables that replaced each other, and iterating over each element in question with this.each(...):
(function ($) {
$.fn.myPlugin = function () {
return this.each(function () {
// do stuff
});
};
})(jQuery);

jQuery monitoring form field created by AJAX query

Preface: I am sure this is incredibly simple, but I have searched this site & the jQuery site and can't figure out the right search term to get an answer - please excuse my ignorance!
I am adding additional form fields using jQuery's ajax function and need to then apply additional ajax functions to those fields but can't seem to get jQuery to monitor these on the fly form fields.
How can I get jQuery to use these new fields?
$(document).ready(function() {
$('#formField').hide();
$('.lnk').click(function() {
var t = this.id;
$('#formField').show(400);
$('#form').load('loader.php?val=' + t);
});
//This works fine if the field is already present
var name = $('#name');
var email = $('#email');
$('#uid').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(function () {
$.ajax({
url: 'loader.php',
data: 'action=getUser&uid=' + t.value,
type: 'get',
success: function (j) {
va = j.split("|");
displayname = va[1];
mail = va[2];
name.val(displayname);
email.val(mail);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
So if the is present in the basic html page the function works, but if it arrives by the $.load function it doesn't - presumably because $(document).ready has already started.
I did try:
$(document).ready(function() {
$('#formField').hide();
$('.lnk').click(function() {
var t = this.id;
$('#formField').show(400);
$('#form').load('loader.php?val=' + t);
prepUid();
});
});
function prepUid(){
var name = $('#name');
var email = $('#email');
$('#uid').keyup(function () {
snip...........
But it didn't seem to work...
I think you are close. You need to add your keyup handler once the .load call is complete. Try changing this...
$('#form').load('loader.php?val=' + t);
prepUid();
To this...
$('#form').load('loader.php?val=' + t, null, prepUid);
What you are looking for is the jquery live function.
Attach a handler to the event for all elements which match the current selector, now or in the future
You can do something like this:
$('.clickme').live('click', function() {// Live handler called.});
and then add something using the DOM
$('body').append('<div class="clickme">Another target</div>');
When you click the div added above it will trigger the click handler as you expect with statically loaded dom nodes.
You can read more here: http://api.jquery.com/live/

Resources