Can't do anything with .load()-ed content in jQuery? - php

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.

Related

Javascript not executing after Ajax call

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) {

jQuery scrollbar plugin not working on Ajax loaded content

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.

dynamic loading content containing javascript

I want to add a progress bar before my web page's content loads, so I thought of loading it dynamically via javascript. This content has embedded javascript in its html. I tried using jquery.load() which works perfectly besides the fact that it does not support the js that doesn''t work on the returned content
just to make it clear, what i'm doing is something like this to load all the content:
$("#contentid").html("progressBar.gif");
$("#contentid").load(script.php #content)
$("#contentid").show();
and inside the content returned from script.php there are js calls such as:
jquery.load (to crawl for data and displaying it when ready)
document.getElementById('some_div') (for chart api)
snippets that load widgets
I've been trying to work around with using jquery.ajax though not sure if\how its possible with it yet. would love for some input on that.should i be able to achieve that with it?
Any other idea that might show a progress bar till the script's content is loaded will be great. I'm trying to reduce changes in the code structure, since this long load happens only sometimes.
Thanks.
You may add a div with the progress bar, covering all the page, and remove it after the page is loaded, using:
$(window).load(function() {
$('#progressbar').remove();
});
JQuery's load method takes a callback function as an argument. That function will get called when the load is completed, so you can hide your progress bar at that point. Here is an example from their API docs:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
In your case, it would be something like:
$("#contentid").load(script.php, function(){
$("#contentid").hide();
});

How to initiate javascript in jQuery ajax-loaded content in IE8

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.

Javascript Tabber Reload

I've got some dynamic content inside a tabber (http://www.barelyfitz.com/projects/tabber/).
All works fine, but I want to reload the div which contains the tabber. When I do this, using jQuery AJAX, the data updates, but the tabs are no longer formed. Do I have to reload the javascript elements of the page, and if so how do I got about doing this?
Thanks! :)
Sparkles*
Your AJAX function is probably replacing the contents of the div with new elements (so they lose any initialization that you've done).
In your AJAX callback, just re-initialize tabber. From glancing at their web-page it looks like you just need to call the function tabberAutomatic(tabberOptions);
I think something like this will do the trick:
$("#myDiv").load("/my/remote/data.json", function(){
tabberAutomatic();
});

Categories