I know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I'm working on a Wordpress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think - if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won't work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being 'connected' to the JS anymore but I'm not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you're probably going to ask what I've already tried, but if I'm honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn't currently work after the Ajax call). The script is started by the standard $(document).ready(function() { statement.
Thanks for any help :)
First, you need to accept the event object as an argument.
$(".page-feed").on('click', '.post-nav>a', function(event) {
Next, by using the jQuery event object, you can simplify the next line because event is normalized by jQuery to work cross-browser.
event.preventDefault();
Now, as far as it working on the first click but not after, that's likely because .page-feed is a dynamic element. You'll need to instead select an element that is an ancestor of .post-content. document is a decent replacement, but it would be better if you picked one more local.
$(document).on('click', '.post-nav>a', function(event) {
Related
We currently search through a form for contacts, and AJAX is used to display the results from a PHP file below the form (on the same page). The form's onsubmit attribute includes a return:false value to allow the AJAX code to complete.
The results appear 'below the fold' and I'd like the focus to jump down to an ID (#peopleResults) but can't manage this; instead, it stays at the top of the parent page.
Should I be trying something in the actual PHP file or in the AJAX call (to the PHP file) to achieve this?
I already tried <script>window.location.hash = "peopleResults";</script> in the PHP file and referencing results.php#peopleResults in the AJAX call, but neither worked.
Is this possible? I guess I am trying to do the equivalent of appending #peopleResults to the URL upon pressing Submit (without the URL necessary changing)...
I already tried <script>window.location.hash = "peopleResults";</script>
location.hash includes the # – both when reading from it, as well when you set a new value.
So
window.location.hash = "#peopleResults"
would be the correct way to tell the browser to jump to an element with the ID (or anchor name) peopleResults.
I think you want to achieve this please check the fiddle.
This is done without using hash. As you just want to view the result after Ajax.
By this you don't need to change the URL.
Based on the reply to my comment, it would seem you're a little foggy on the AJAX portion too. From the documentation:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
//this is where you need to add your data to the div
//after the data is in the div, scroll to it.
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
You can see, the function where I added the comments is where you need to do the scrolling. After you populate the div (how ever you're doing that), then just use the suggestion Learner Student or phpisuber01 made of scrolling to it:
$("html, body").animate({ scrollTop: $("#peopleResults").scrollTop() }, 1000);
jQuery AJAX documentation: https://api.jquery.com/jQuery.ajax/
jQuery scrollTop documentation: https://api.jquery.com/scrollTop/
The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.
I'm facing an interesting problem where everything works flawlessly. I console.log every step and it plays out just the way it should. But! I have a #div into what I .load(a-file.php). Now that "a-file.php" includes HTML mark-up as well, more specifically certain links that I'd like to make "active" onload.
Scenario; page load happens, Javascript loads and loads a file into the div. That div now has tabs and I'd like the first tab to be in an "active" state which requires me to addClass('active');. But the following seems to have no effect
$('#content').load('file.php'); // works.
$('#content a[rel="weird-page"]').addClass('active'); // does not work.
Any kind of help, even remotely nailing it, is appreciated.
change to:
$('#content').load('file.php', function() {
$('#content a[rel="weird-page"]').addClass('active');
});
jQuery load() works asynchronously and therefore your addClass() method is being called before load() has completed.
Using the load() callback function it will ensure your content has loaded:
$('#content').load('file.php', function() {
$(this).find('a[rel="weird-page"]').addClass('active');
});
shameless-plug-warning: I wrote a blog post about jQuery callback functions which you might find useful.
I am developing a web-page in PHP that needs following functionality:
1. When User click on "Say Thanks" it should be changed with "Done!".
2. At the same time I want to call an action in indexController.
3. At this time I want to show "loading...."
4. The current page has a lot of dynamic contents that should also not change.
Please suggest me what should I do to complete above tasks......
I figure you need an AJAX call. I usually do that for loading comments and such when you press "more". In my case, there's an empty div and an <a> tag with the link to the comments view (with a separate action, ofc). Then I use jQuery for the AJAX magic:
$(function() {
$("a.CommentsListBtn").click(function() {
var tmpHref = $(this).attr("href");
var tmpLayer = $(this).parent().children("div.CommentsList");
tmpLayer.load(tmpHref, function() {
tmpLayer.stop().slideDown("medium");
});
return false;
});
});
I hope this helps.
Learn to use JQuery, JQuery UI. It isn't that hard! What I think you need to learn is the following for your problem:
.click()
.html()
jQuery.get()
I'm facing a trouble with jquery ajax under IE8. I have a form which at the base level displays a list of few items, each with buttons to edit and remove. The list, along with those two buttons, is loaded via jquery ajax call. Although it works fine on Firefox and Chrome, on IE8 it won't trigger functions behind edit or remove buttons.
So basically, on a base page, jquery works and loads the list. Within that list tho, jQuery doesn't work as it won't trigger edit or remove functions
I have a similar problem with the modal window call. IE8 is able to open the modal window (content is loaded with jquery ajax) but won't trigger any function within the content of the modal
Example of a simple call
$('#form-modal').load('/form/' + path + '?id=' + id).modal();
This works on IE8 from the base page, but doesn't when triggered within ajax-loaded content
All js scripts definitions are being loaded in the <head> of the main base page. I tried adding definition to the ajax-loaded file header, but didn't help so it must be something else
Any ideas? If you need more details, will gladly provide
Let me show you the easiest example. Each item on the list loaded with ajax has a 'remove' button.
Remove
DeleteItem definition is in external lib.js file
function deleteItem(id){
$.ajax({
type: "POST",
url: "/ajax/deleteitem.php",
data: "id=" + id,
success: function(msg){
loadItemsList();
}
});
}
This is it... That simply doesn't work on IE8... Nothing happens, not even javascript error. Same thing works no problem on Firefox and Chrome
It would be nice if you show the event handlers for those buttons, since if you're using bind(); for example, it loads when the dom is ready, and your ajax call is made. That means that the dom elements loaded through the ajax call wasn't there when bind was called to bind the buttons.
The solution to this is to use live();
$(".button").live("click", function () {
// do stuff
});
I don't know what event binder you're using, but if you're using anything other than live, you could try live and it should work.
EDIT
Read my comment first on the alert(id), if your function doesn't run at all in IE8, try doing this instead. Give the link element the id instead like this
<a id="item_10" href="#">Remove</a>
Then somewhere in your javascript
$("document").ready( function () {
$("a").live("click", deleteItem);
});
function deleteItem (event) {
event.preventDefault();
var id;
id = $(this).attr("id").replace("item_", "");
//this will now provide you with the current id
console.log(id);
your ajax-stuff here..
}
This should work in IE8, no problem. You might wanna specify the selector though for the click event by giving all the delete links some class or something.