facebook-1559314183
facebook-1559314183

Reputation: 29

Pass value to ajax from a A tag which is already loaded by another ajax

I want to pass a value to ajax from Anchor tag which was already loaded by another ajax. I have a page called profilesearch.php. i have this code in the header

function loadData(page){
$.ajax({
type: "POST",
url: "load_data.php",
data: 'page='+page+'&user='+<?php echo json_encode($_GET['uid']); ?>,
success: function(msg){
    $("#container").ajaxComplete(function(event, request, settings){
        loading_hide();
        $("#container").html(msg);
        });
    }
});
}

This piece of code will return a set div to the #container from load_data.php file has pagination. Each div will have a Anchor tag with that, ID of the Anchor tag is #myAnchor. When user click that #myAnchor it should again execute a another ajax to the file updateAjax.php.

<script type="text/javascript">
$(document).ready(function(){
    $("#myAnchor").click(function(){
        alert("hi");
        $.ajax({
        url: "updateAjax.php",
        data: 'varName=hi',
        success: function(upmsg){
            $("#myAnchor").html(upmsg);
        }
        });
    });
});
</script>

When i have a anchor tag in the same page i.e profilesearch.php this works fine.. but when i load a Anchor from another ajax request its not working.

Upvotes: 0

Views: 905

Answers (2)

tymeJV
tymeJV

Reputation: 104775

Try calling the click function like so:

$(document).on('click', '#myAnchor', function(){ 
    //code here
)};

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use event delegation in cases where dynamic elements are involved. You can use .on() to achieve this.

$(document).ready(function(){
    $("#container").on('click', '#myAnchor', function(){
        alert("hi");
        $.ajax({
        url: "updateAjax.php",
        data: 'varName=hi',
        success: function(upmsg){
            $("#myAnchor").html(upmsg);
        }
        });
    });
});

Upvotes: 1

Related Questions