views:

61

answers:

2

I have index.php like this:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<a href='one.php' class='ajax'>One</a>

<div id="workspace">workspace</div>

one.php

<?php
$arr = array ( "workspace" => "<a href='two.php' class='ajax'>two</a>" );
echo json_encode($arr);
?>

two.php

<?php 
$arr = array( 'workspace' => "Hello World" );
echo json_encode($arr);
?>

ajax.js

jQuery(document).ready(function(){
    jQuery('.ajax').click(function(event) {
        event.preventDefault();
        // load the href attribute of the link that was clicked
        jQuery.getJSON(this.href, function(snippets) {
            for(var id in snippets) {
                // updated to deal with any type of HTML
                jQuery('#' + id).html(snippets[id]);
            }
        });
    });
});

When index.php is loaded, there is a link(One) and a DIV(workspace). When I click 'One' link then content of one.php is called and link 'Two' appeared in 'workspace' DIV successfully.

But now when I click link 'Two' then 'Hello World' does not appear in 'workspace' DIV and opened separately without AJAX call.

How to force this code to replace content of workspace DIV with 'Hello World' using link 'TWO' with above flow?

Thanks

A: 

The problem is that the init method that makes the ".ajax" links so magical is only being called once, when the document loads. When you replace the html the magic is lost.

Try this:

function assignLinks() {

    jQuery('.ajax').click(function(event) {
            event.preventDefault();
            // load the href attribute of the link that was clicked
            jQuery.getJSON(this.href, function(snippets) {
                for(var id in snippets) {

                    // updated to deal with any type of HTML
                    jQuery('#' + id).html(snippets[id]).click( function() {
                        assignLinks();
                    });
                }
            });
        });

}

jQuery(document).ready(function() {
    assignLinks();        
});

Or, just use live (as stated below).

Phillip Cohen
I tried but no luck.
NAVEED
Ah, you're right. The problem is that the init method that looks at ".ajax" is only being called once, when the document loads (so the subsequent changes aren't affected). Will update in a sec...
Phillip Cohen
+2  A: 

Try the live() method instead of click:

jQuery('.ajax').live('click', function(event) {
  // your code
});

The live is used when the content you have assigned events to is either present or is added/loaded later.

Sarfraz
Thanks Sarfraz. Its working.
NAVEED
@NAVEED: You are welcome :)
Sarfraz