dynamic loading content containing javascript - php

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

Related

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.

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

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.

Loading pages into a div with JQuery, existing Javascript not working

I have a page I'm working on where a user clicks a link and it loads a new php file into an existing div. It works but the page that loads into the div will not function with existing Javascript stuff in the page.
I can include the
<script type="text/javascript" src="js/admin.js"></script>
into the loaded pages but when you flick back and forth between the pages I notice that RAM usage starts to go up and up, so I don't think this is the best way of doing it.
Any ideas how the loaded page can function with the already-loaded javascript from the index page?
Thanks!
bind your events like this :
$(document).on({
"event" : function(e) {},
...
}, "selector");
If you are using bind or click type events change to using something like on (or live or delegate if you are required to use jquery version less than 1.9)
OR/AND
In your function that loads in the page via ajax provide a call back that initiates only what is needed. Example:
$('#myDiv').load('ajax/page.php', function(){
$('#myDiv a').customPlugin('whatever');
$('#myDiv button').bind('click', function(){
window.open('http://www.google.com/', 'some-window');
});
});

Is there a way to define a function permanently in jQuery?

I'm working on a site that passes information to my server that returns a page, however I have to re-define the click listener every time I reload the page because jQuery controls all my clicks on every page, so I' m wondering is there a way to permanently define a function?
jQuery code:
$(function(){
$('.lvl1Links').on('click',function(event) {
event.preventDefault();
$('pload').html('<img src="source/image/lbl.gif">');
var page = $(this).attr('id');
var huh = $('input:hidden').val();
var data = 'pop='+huh+'&page='+page;
$.post('source/php/bots/authorize.php',data,function(data){
$('#pager_master_div').html(data).slideDown();
$('pload').html('');
});
});
});
Being a stateless platform, every time the page loads you need to rebind things like this. Here's the pattern I use to make it easier, though:
If this is common across an area of your site, put this type of stuff into an init function in the common file. e.g.
global.js:
function InitSalesPageOrWhatever(){
$(function(){ foo; });
OtherStuffThatRunsOnEverySalesPageLoad();
}
Then in the script block on your pages, e.g. SalesPage:
InitSalesPageOrWhatever();
That's it--just one line in your content pages. Beyond the benefit of the content pages being nice and clean, that big clump of JS can now be cached by the user's browser, making the load on you less and their experience faster.
jQuery (and all Javascript) runs on the client side where permanence is unavailable. There are two ways to approach the permanence you seek.
Write a jQuery plugin and include it in your page.
Write your click handler once, and use your server-side code/scripting language to include it in every HTML page. An example PHP include is here.
This may be a good time to consider HTML templates -- documents that contain standard HTML (header, footer, navigation, etc) that should be included in every page of your site.

jQuery load ...execute parent js

I have a PHP query that displays the first 30 documents, then an anhor which loads the rest of the documents using jQuery load.
Although, the parent uses javascript for some effects. Although once loaded onto the document it doesn't seem to inherit it's script tags.
is there any solution for this?
you have to put your "effects" into a function, then in the success of the load you have to call that function again.
function effects(){
//all your effects
}
$('#result').load('ajax/test.html', function() {
effects();
});

Categories