Calm Sea
Calm Sea

Reputation: 181

load content of file using ajax/jquery

I want when click on one of the links in my dive to load sub links from .php file .This works , but I want when click on "Home" link , the original links back again. This also works , but when I re click on one of these links , the sub links does not loaded any more from the .php file .

html page :

<script>
    $(document).ready(function(){
        $(".link").click(function(){
            var value = $(this).attr("href");
            var linkName = {'href':value};
            alert(value);

            $.ajax({
                type: "POST",
                url: 'sublinks.php',
                data :linkName,
                success: function(response){
                    $('#target').html(response);
                }
            });
        }) ;
    })
</script>
.
.
.
<ul>
    <li><a href="#home" class="link">Home</a></li>
</ul>

<ul id="target">
    <li><a href="#book" class="link">books</a></li>
    <li><a href="#auth" class="link">authors</a></li>
</ul>

sublinks.php file

<html>
<body>
    <?php
        $name = $_POST['href'];
        $books = array('web','coocking','coding');
        $authers = array(111,222,333);

        if ($name == "#books") {
            foreach ($books as $v)
                echo "<li><a href=\"#eroom\">".$v."</li></a>";
        }
        else if ($name == "#authors") {
            foreach ($authers as $v)
                echo "<li><a href=\"#sroom\">".$v."</li></a>";
        }
        else if ($name == "#home") {
            echo "<li><a  href=\"#book\" class=\"link\">books</li></a>";
            echo "<li><a  href=\"#auth\" class=\"link\">authers</li></a>";
        }
    ?>
</body>
</html>

Upvotes: 0

Views: 202

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

try:

$('#target').on( 'click', 'a.link', function () { 
  ..your code here
});

Edit: I meant change following:

$(".link").click(function(){

to

$('#target').on( 'click', 'a.link', function () { 

Added: you could also do

$(document).on('click', 'a.link', function() {
    .... rest of your code
});

Edit: This code will add a delegation so that as more a.link elements are added within #target they will have their click handler bound as well.

Upvotes: 1

Related Questions