Ajax breaks jQuery scripts on page - php

I'm currently working on a website that you'll find here: http://steadfastdesignfirm.com/rgw/. I used an ajax effect that I found online at CSS-Tricks to dynamically load content from another php page and animate it (fade in and fade out) when a navigation tab is clicked.
I have managed to get this working fine, as you will see (please note the only two working pages are "Home" and "Experience RGW"), however, all of the jQuery scripts in my document that apply to elements within the div that reloads are broken when the content is dynamically generated.
As a quick example, take a look at the text resize tool beneath the image rotator on the home page and try changing the font size. Now, click on the "Experience RGW" tab and scroll down to the text resize tool again. Notice that now that we've loaded in experience.php dynamically within the "#ajax" div, the script doesn't work. Also, if you click on the "Home" link now, you will also notice that the image rotator doesn't work.
I've looked high and low online and through multiple forums to try and figure out how to fix this, and I believe I have to incorporate the jQuery .live function, to apply the script to any element, whether it's currently visible or not. Otherwise, document.ready only runs the scripts once after the DOM loads and will not affect the ajax loaded content. Is that correct? If so, how do I apply that to multiple jQuery files executed on my page?
Well, this is totally driving me crazy and I've tried hard to get it, but I just can't quite figure it out. I'm fairly new to jQuery, but am trying to learn fast. I would post some of the code here, but there is a lot involved in this question. :)
If anyone would be willing to shoot out a quick answer, or a few lines of code, I'd greatly appreciate it.
FYI: The script that runs the ajax effect is in ./scripts/page.js. Also, please remember that I currently have only the Home page and Experience RGW page working correctly, so please don't waste time trying to diagnose problems on the other pages. I haven't gotten to them yet. :)
Here is a link to some of the code on jsfiddle: http://jsfiddle.net/taylortsantles/R33YV/.
Thanks,
Taylor

I'm behind a proxy and can't see your page, but it sounds like the events are not being re-attached to the content created through ajax.
I'll try to explain, when your page loads the first time, you are attaching jQuery events to DOM objects on document.ready(), this function will be called only once.
Every time you drop DOM objects and create new ones with the ajax response, these new objects never get jQuery events attached again, since the document.ready() function didn't fire.
You can try putting your event-attaching code in a different function and invoke that function on document.ready() AND after every DOM modification (your ajax call to change the tab content).
Hope it helps.

The problem is a breakdown in the order of executing code.
page loads
load event fires and sets up elements
click event
ajax loads the new page
The new page doesn't have any events set to it. Two solutions
use "live" links in the window.load event callback
use run the page load code again.
Solution 1 is nice but if you have an specific plugin used then it won't be the total solution.
Solution 2 can be implemented by pulling out your code in window.load and wrapping in another function. Just all it onload and then in the callback when the ajax loads.
I know how frustrating is can be. I hope this helps.

You need to rebind any events after dynamically loading in elements to a page, as Javascript sees these as totally new DOM elements.
You can achieve this by modifying the code you use to update the page:
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#ajax")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #ajax", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav li").removeClass("on");
$("nav a[href='"+newHash+"']").parent().addClass("on");
// Rebind any events
documenttextsizer.setup("text-resize");
});
});
};
});
This applies to any events that happen WITHIN the updated elements in the page. So after the comment "//Rebind any events" you can add others as they are required! Hope that helps :)

Related

jquery button with .click and .load not working correctly

I have a small problem with a jquery function and I can't figure out where I'm going wrong with it, I'm using .load to pull another page into a div for the second time using a button with a .click() function. The problem here is when I click the button the data I want flashes up and is then replaced with the data that is loaded when I first navigate to the page, however if I bind the .click to:
<p>peter paragraph</p>
The page will load fine without incident.
The jquery function is this:
$(document).ready(function() {
$("p").click(function(){
alert("buttonthe1st");
$('#jam').load('register.php');
alert("buttonthe2nd");
});
});
I was using the alerts to test to see if it was working originally, the function appears to be working a long with the actual load event when I tested them with the paragraph and when I tried them in googles developer console.
As I typed the above out I just realised when I was testing it, the URL and the page refreshed even if there was no function or onclick even tied to the button in question. Which explains why I'm having this problem now, is there a way to resolve this?
P.S. I appologise for making this so vague.
I am a little confused as to why clicking on a paragraph element would cause a page to reload but if you are in fact talking about a button element you might find the preventDefault function helpful. Try using that within the function you are binding to "onclick" and see if it makes any difference

Using Ajax to flush obflush

Ok so I have created a wizard and everything works great. But I have one little piece that seems to 'bother' me if you will.
In the last step of the wizard I build, it uses obflush to process data onto the screen
to show some actions happening. But the problem with that is, that the 'entire' page doesn't load until the obflush process is done, and then the page all lines up nicely and such.
Im wondering if there is such a way that maybe ajax can flush the obflush process?
Maybe this is completely wrong but this is how I can envision it happening.
User goes thru the wizard and gets to the final page
The entire page loads
At the end of the page is some ajax code to apply to a tag maybe
The ajax is refreshing itself every second to check against the update of the obflush and then outputting what the obflush has outputted to the screen.
Does that make sense?
Any insight is greatly appreciated.
Thanks
This question is about how to load part of a web page with Ajax. In particular, how to load the structure of a page, and then fill in the details with Ajax calls.
I assume the intention is for the structure to be loaded quickly because it does actually have some content, and then load parts of the page that take a long time to process. Otherwise the effect on screen will be that loading is actually slower.
I would use the JavaScript library jQuery to help with this, although it can be done without any libraries as shown in this question.
The browser makes a web page request and the server responds like it would normally, but just with the structure of the page
Within the basically empty page that was loaded, jQuery will then make an Ajax call with load() that will load the response from a URL into the specified HTML section.
The code would look like this, where my-intro-div is the id of a regular HTML div tag:
$(function() {
var myIntroDiv = $('#my-intro-div');
myIntroDiv.load('/my_intro_div.php');
});
The PHP script my_intro_div.php returns the HTML that is meant to be displayed inside the my-intro-div tag
There are some good examples in the jQuery documentation here:
http://api.jquery.com/load/
jQuery can help with a tonne of other things too. It has a tiny learning curve that can be a little steep, but after that I've found that it is the most intuitive "language" I work with.

jQuery Mobile Form Validation with PHP Failing

I'm trying to add some validation to some form fields in a jQuery Mobile site I'm building with a PHP back end.
I've done this in the past successfully using the jquery.validate plugin but I'm having trouble getting this to work with jQuery Mobile.
The validation is working in this jsFiddle page:
http://jsfiddle.net/GeX5C/5/
but I'm having trouble getting it to fire when I click the submit button from the hosted PHP page. From what I've read I can't use the usual:
$(document).ready(function(){
approach but not sure what to replace this with?
Would really appreciate any assistance here.
Thanks
2 options, in the event document ready is not supported for whatever reason..
one try the load event on the window, which will wait til everything is loaded and completely rendered, similar to the ready function but waits just that much longer course im paraphrasing but hopefully you get the point.. its applied the same as the ready function.
$(window).load(function(){
// Your code here
});
second option is dont use any load/ready. just make a function that fires off as the final line of your code, should whatever your doing truely not require the page to actually be fully rendered to run. logic to this is make a function then in the last lines call the function.
also try to keep a mass majority of your javascript especially pieces that require other things to load first at the bottom of your page just above the final body tag. Yea theres hot debate over this some people insist top is better while others insist bottom.. me Im a bottom guy think about the logic, when downloading the page downloads top to bottom in a sense correct? so.. put the heavier of the weight at the bottom such as external scripts. anyway im getting off point, hopefully this helps some what.
FYI this is js code that works for the form validation:
$('#id-for-the-page-element').live( 'pageinit',function(event){
$('#id-for-the-form').validate(options);
});
Hope this helps someone else.

Scroll text down after clicking

I am having difficulties in the following problem:
I have a screen in PHP which displays a list of some records when I choose any of these
records (by clicking) it gives me a web site to share the data with this record. So far, it works.
I need to click on some of these records, instead of him
open another page, scroll down the screen and the record data to appear in the same screen, ie without opening another window.
Do you have any idea how to do this?
Thanks
You'll need to have a DIV at the bottom of the page, which will be completed by using an Ajax call and some javascript or jquery.
Without going into too much detail, heres what needs to happen:
User clicks a link which fires off an ajax request.
The backend PHP script takes the ajax call and generates either XML or pure HTML and returns the data.
JQuery or JavaScript on the original page takes the return and populates the empty DIV at the bottom of the page.
Regards
It sounds like you'll need to use ajax to pull this off.
I would personally suggest starting with reading up on the jQuery javascript library if you are not familiar with it already. It provides a very good set of ajax tools to work with.
Create a DIV layer on the bottom of the page. Use a simple AJAX library like this
Create a new php page that will only load a new record based on the recordID and call this page on the onclick method of your link that is now opening in the new window
I would try adding some jQuery to your page to handle this effect.
If you do add jQuery here is a function written to do just that:
http://pastebin.com/SeMHwSgg
Call the script like so:
Where a is the record you are having them click on and href="[some anchor]" located at the spot on the screen where you want the scrolling to stop:
<a id="gotop" href="#" onclick="goTop();return false;">click here</a>
So
Indeed, there is no error, it just does not have the effect that (scroll down the screen and show the record data). For now, it only shows the record open in another window.

Assigning class to div element based on hash fragment in URL

I hope someone can help!
My website: http://www.richardmilne.net
I have a wordpress site set up to use the iinclude plugin to display individual pages all on the front page. This works great but I don't want users to access individual pages, ie "site.com/page". If a user visits "site.com/page" (eg from a search result), I want them to be redirected to "site.com/#location", have the window scroll to the correct location, and trigger the jquery slider. (see link above)
I was planning on using .htaccess to redirect the page. After that from what I've gathered I need to use a bit of javascript trickery to trigger the desired div to slide open. In my case this is simply a case of changing it's class to "toggle_initial", which the jquery script animates after an 800ms delay on page load. (again, see the link above, which already uses this to load the "recent posts" section when you first visit. Just so you know this is a jquery-UI plugin).
It's the bit in the middle I can't get my head round. What I've read so far tells me I can't do this with php which was my first approach, as "PHP_SELF" ignores the "#location" bit of the URL. This leaves javascript up to the task of changing the div's class, I've found these links which I'm sure contain some hints for me, but as a javascript novice I can't make head nor tail of how to apply them to my site:
Adding a class to an a element with a particular href using hash
doing substring in window.location.hash
Any tips would be greatly appreciated, cheers!
You'll probably want to use JQuery window.location.hash to get any values after the hash tag.
See a few tutorials below:
http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
http://www.using-jquery.com/2011/01/ajax-navigation-window-location-hash/
Step 1. Get the anchor element from the url using javascript. window.location.href
Step 2. Change the class of your target h2 using jQuery. Code assumes that div id and anchor are identical.
$(document).ready( function() {
var anchor = yourCodeToFindAnchor;
$('#' + anchor).addClass('active');
});
I recommend http://benalman.com/projects/jquery-bbq-plugin/
It easily allows you to hook up all kind of jQuery actions to the hash object.
This should get you started: http://benalman.com/code/projects/jquery-bbq/examples/fragment-basic/

Categories