Rumman Ahmed Rumman Ahmed - 6 months ago 15
Javascript Question

Run jQuery on JSON data

I have a AJAX call function assigned to a tab link, which will get the result from a php page and then displayed on the page.

This is the ajax code below

$(document).ready(function(){
$(".resolved_tab_copy").click(function(){
$.ajax({
type:"POST",
url:"dynamic_tab.php",
async:true,
success:function(data){
$('.main_display_4resolve').html(data);
}
});
console.log("Hello");
});
});


data retrieved is formatted as HTML element and I want to be able to run jQuery click and various other event on those elements
data retrieved look like following..

echo '<div class="ticket_div">
<div class="menu_wrapper">
<div class="resolved_diag_click" id="',$each_issue['issue_id'],'">Notes</div>
<div class="resolved_diag_res_click" id="',$each_issue['issue_id'],'">Resources</div>
</div>
<div class="resolved_diag_show" id="resolved_notes_displayDiv',$each_issue['issue_id'],'">
<div class="resolved_diag_result" id="resolved_diag_resultID',$each_issue['issue_id'],'">';
$target_issueid=$each_issue['issue_id'];
$diag_list=get_diag_result($target_issueid);

foreach($diag_list as $each_diag){
echo '<div class="diag_txt">';
$name_id=$each_diag['diag_logger'];
$name_list=get_name($name_id);
foreach($name_list as $each_name){
echo '<div class="resolved_diag_logger">',$each_name['fname'],' ',$each_name['lname'],'</div>';
}
echo '<div class="resolved_diag_time">',$each_diag['diag_time'],'</div>';
echo '<div class="resolved_diag_desc">',$each_diag['diag_desc'],'</div>';
echo '</div>';
};


echo '<ul class="tkt_ctrl">
<li class="resolved_tkt_ctrl_cmnt_click_',$each_issue['issue_status'],'" id="resolved_cmnt_clickid',$each_issue['issue_id'],'" alt="',$each_issue['issue_status'],'">Comment</li>
<li class="resolved_tkt_ctrl_li_',$each_issue['issue_status'],'" alt="',$each_issue['issue_status'],'">Email</li>
<li class="resolved_tkt_ctrl_resolve_',$each_issue['issue_status'],'" id="resolved_resolveID',$each_issue['issue_id'],'" alt="',$each_issue['issue_status'],'">Resolved</li>
</ul>
</div>


i would like to be able to run jQuery event on

<div class="resolved_diag_click" and display <div class="resolved_diag_show".


This page when static all jquery works but when retrieved via ajax call jQuery events not working..

I must have missed something very silly I could not get my head around that..
if anyone could show me the right direction that would be life saving..
Also I am researching on jQuery .on and .live event, is that what we should try..
Thanks

Answer

Use jquery's .on function. The elements will have the event listener attached to them even when you create them after page load.

$("body").on("click", ".resolved_diag_click", function (e) {
    // handle event here
    alert("foo");
});
Comments