dole doug
dole doug

Reputation: 36048

trigger events after an ajax request with jquery

I have a html page which contain a jQuery script and a AJAX request. On my page I have some span elements with the class 'loading_span'. On a click to a href, an ajax process is executed. That process also generates some spans with the class: 'loading_span'. The problem is that my jQuery script doesn't trigger the new added span elemnts by the ajax request.

The queswtion is: Why my script doesn't see that new element with class 'loading_span' were added?

In the followong I'll paste my code:

/* file js/javascript.js */
$(document).ready(function() {

    $.ajaxSetup ({
        cache: false
    });

    $('#show-more').click( function() {
    $.ajax({
        url: $(this).attr('href'),
        success: function(msg){
            $('#all_span').append().html(msg);
        },
        dataType: "Html"
    });
    return false;
});


    $('.loading_span').each(function(index, span){
        console.log($(this).attr('id'));
    });
});

the index.php file:

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script src="js/script.js" ></script>   
        <style type="text/css">
            .loading_span {
                display: list-item;
            }
        </style>
    </head>
    <body>
        <div id="all_span">
        <?php

        for($i=0;$i<5;$i++)
            echo "<span class='loading_span' id='id$i'>span$i</span>";
        ?>
            <a href="ajax.php" id="show-more">show_more</a>
        </div>
    </body>

and the ajax.pho file content

for ($i = 0; $i < 5; $i++)
    echo "<span class='loading_span' id='ajax$i'>ajax$i</span>";

Upvotes: 0

Views: 1527

Answers (3)

The Alpha
The Alpha

Reputation: 146191

You should use

$('#all_span').append(msg);

instead of

$('#all_span').append().html(msg);

and change your success callback to

success: function(msg){
        $('#all_span').append(msg);
        $('.loading_span').each(function(index, span){
            console.log($(this).attr('id'));
        });
},

Upvotes: 1

j08691
j08691

Reputation: 207901

Your $('.loading_span').each... is executing prior to your AJAX call finishing which is why it's doing what it's doing. You can move that code into the success event of your AJAX call so it will be applied once the new elements are added to the DOM.

Upvotes: 0

user1269989
user1269989

Reputation: 117

You can use after element to add element after loading_span.

See below url for just Javascript part. http://jsfiddle.net/vkTHK/1/

I still cannot figure out what you are trying to achieve. if it does not satisfy your need please elaborate on part or provide JS fiddle URL so i can help.

Upvotes: 1

Related Questions