hash in url to deep linking with ajax - 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;
});
});

Related

Init js after Ajax call

I have a small Javascript used to swap images using a href links. Everything is OK except when I call those a ref inside the page using Ajax. I need to find a way to initialize again the script after calling new links.
Here is the JS:
<script type="text/javascript">
$('a.thumbnail').click(function(){
var src = $(this).attr('href');
if (src != $('img#largeImg').attr('src').replace(/\?(.*)/,'')){
$('img#largeImg').stop().animate({
opacity: '0'
}, function(){
$(this).attr('src', src+'?'+Math.floor(Math.random()*(10*100)));
}).load(function(){
$(this).stop().animate({
opacity: '1'
});
});
}
return false;
});
Thank you
You need to delegate the events.
Turn this:
$('a.thumbnail').click(function(){ /*...*/ });
into this:
$('#someWrapperContainer').on('click', 'a.thumbnail', function(){ /*...*/ });
Make sure you're using jQuery 1.7+

Prototype.js event observe click intercept and stop propagation

I have a page that is built around a wrapper with some very defined logic. There is a Save button on the bottom of the wrapped form that looks like this:
<form>
... my page goes here...
<input id="submitBtnSaveId" type="button" onclick="submitPage('save', 'auto', event)" value="Save">
</form>
This cannot change...
Now, I'm writing some javascript into the page that gets loaded in "...my page goes here...". The code loads great and runs as expected. It does some work around the form elements and I've even injected some on-page validation. This is where I'm stuck. I'm trying to "intercept" the onclick and stop the page from calling "submitPage()" if the validation fails. I'm using prototype.js, so I've tried all variations and combinations like this:
document.observe("dom:loaded", function() {
Element.observe('submitBtnSaveId', 'click', function (e) {
console.log('Noticed a submit taking place... please make it stop!');
//validateForm(e);
Event.stop(e);
e.stopPropagation();
e.cancelBubble = true;
console.log(e);
alert('Stop the default submit!');
return false;
}, false);
});
Nothing stops the "submitPage()" from being called! The observe actually works and triggers the console message and shows the alert for a second. Then the "submitPage()" kicks in and everything goes bye-bye. I've removed the onclick attached to the button in Firebug, and my validation and alert all work as intended, so it leads me to think that the propagation isn't really being stopped for the onclick?
What am I missing?
So based on the fact that you can't change the HTML - here's an idea.
leave your current javascript as is to catch the click event - but add this to the dom:loaded event
$('submitBtnSaveId').writeAttribute('onclick',null);
this will remove the onclick attribute so hopefully the event wont be called
so your javascript will look like this
document.observe("dom:loaded", function() {
$('submitBtnSaveId').writeAttribute('onclick',null);
Element.observe('submitBtnSaveId', 'click', function (e) {
console.log('Noticed a submit taking place... please make it stop!');
//validateForm(e);
Event.stop(e);
e.stopPropagation();
e.cancelBubble = true;
console.log(e);
alert('Stop the default submit!');
return false;
submitPage('save', 'auto', e);
//run submitPage() if all is good
}, false);
});
I took the idea presented by Geek Num 88 and extended it to fully meet my need. I didn't know about the ability to overwrite the attribute, which was great! The problem continued to be that I needed to run submitPage() if all is good, and that method's parameters and call could be different per page. That ended up being trickier than just a simple call on success. Here's my final code:
document.observe("dom:loaded", function() {
var allButtons = $$('input[type=button]');
allButtons.each(function (oneButton) {
if (oneButton.value === 'Save') {
var originalSubmit = oneButton.readAttribute('onclick');
var originalMethod = getMethodName(originalSubmit);
var originalParameters = getMethodParameters(originalSubmit);
oneButton.writeAttribute('onclick', null);
Element.observe(oneButton, 'click', function (e) {
if (validateForm(e)) {
return window[originalMethod].apply(this, originalParameters || []);
}
}, false);
}
});
});
function getMethodName(theMethod) {
return theMethod.substring(0, theMethod.indexOf('('))
}
function getMethodParameters(theMethod) {
var parameterCommaDelimited = theMethod.substring(theMethod.indexOf('(') + 1, theMethod.indexOf(')'));
var parameterArray = parameterCommaDelimited.split(",");
var finalParamArray = [];
parameterArray.forEach(function(oneParam) {
finalParamArray.push(oneParam.trim().replace("'","", 'g'));
});
return finalParamArray;
}

JQuery Ajax, how do I not repeat my code?

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
};

"Load More Posts" with Ajax in wordpress

I am trying to create ajax pagination on Blog Page..
What I need to do is to display 5 posts initially and then load 5 more when "load more posts" link is clicked.
Below is the javascript I am using:
<script>
jQuery(document).ready(function() {
// ajax pagination
jQuery('.nextPage a').live('click', function() {
// if not using wp_pagination, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('.blogPostsWrapper').html('<div><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('.blogPostsWrapper').load(link+' .post')
});
}); // end ready function
</script>
The problem is that when I click the link the old posts get replaced by the new ones, I need to show old posts as well as the new posts...
Here is the Updated jQuery Code which enables the ajax pagination.
jQuery(document).ready(function(){
jQuery('.nextPage a').live('click', function(e){
e.preventDefault();
var link = jQuery(this).attr('href');
jQuery('.blogPostsWrapper').html('Loading...');
jQuery('.blogPostsWrapper').load(link+' .post');
});
});
The only problem now is the old posts get removed, i need to keep both old and new posts..
Here is the final code I used and now everything works perfectly...
// Ajax Pagination
jQuery(document).ready(function($){
$('.nextPage a').live('click', function(e) {
e.preventDefault();
$('.blogPostsWrapper').append("<div class=\"loader\"> </div>");
var link = jQuery(this).attr('href');
var $content = '.blogPostsWrapper';
var $nav_wrap = '.blogPaging';
var $anchor = '.blogPaging .nextPage a';
var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts
$.get(link+'', function(data){
var $timestamp = new Date().getTime();
var $new_content = $($content, data).wrapInner('').html(); // Grab just the content
$('.blogPostsWrapper .loader').remove();
$next_href = $($anchor, data).attr('href'); // Get the new href
$($nav_wrap).before($new_content); // Append the new content
$('#rtz-' + $timestamp).hide().fadeIn('slow'); // Animate load
$('.netxPage a').attr('href', $next_href); // Change the next URL
$('.blogPostsWrapper .blogPaging:last').remove(); // Remove the original navigation
});
});
}); // end ready function
Could you maybe try the following code? This is how I got this working on my own site.
replace:
jQuery('.blogPostsWrapper').load(link+' .post')
with:
$.get(link+' .post', function(data){
$('.blogPostsWrapper').append(data);
});
You should use jQuery append() to add the new posts without using the old ones.
jQuery load() Will replace the data found in your element . Quoted from jQuery API:
.load() sets the HTML contents of the matched element to the returned
data. This means that most uses of the method can be quite simple:

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