Reputation: 753
i have a common js file after I reload html page in ajax request , I cant access the functions in this file , the common JS functions between $(document).ready(function() How can Access them and fire the functions in common file Example :
COMMON JS :
$(document).ready(function() {
$(".agree_btn").click(function(){
alert(123);
});
});
the Function in the phtml page
$('.loadMoreAnswers').live('click', function(event) {
var location_id = $(this).attr('location_id');
var counter= $(this).attr('counter');
$('#loadingAnswer').show();
$.ajax({
type: 'POST',
url: '/daleel/loadmore',
data: 'location_id='+location_id+'&part='+'answers'+'&answerCounter='+counter, //with the page number as a parameter
success: function(msg){
if(msg.length!=0) //if no errors
{ $(this).parent().load("view")
$('#loadingAnswer').remove();
counter+=5;
$('#profile-page-answer').append(msg);
}
else $("#loadingAnswer").remove();
},
dataType: 'html'
});
});
its render the HTML like This :
<a agreed="no" agreed-content-id="63066" class="agree_btn" id="agree-a63066">
Agree
</a>
But when i click on this Link it doesnt run the function in the Common JS file
Upvotes: 7
Views: 22046
Reputation: 1
Embedd document.ready function after the ajax complete. It will re-register the script on the page after ajax call.
Eg:
$.ajax({
url: 'deleteEntry',
data: {'ids': JSON.stringify(getList)},
async: true,
success: function (data) {
location.reload();
},
error: function (data) {
alert('error');
},
complete: function (data) {
//add your script in body here
}
});
Upvotes: -1
Reputation: 31033
rebind the click event handler in the ajax success
success: function(msg){
//your code
$(".agree_btn").bind('click');
}
or you can use delegate
for jQuery versions lower than 1.7 like
$(document).delegate(".agree_btn",'click',function(e){
//your code
});
or of you are using jQuery version 1.7+ use on
method
$(document).on("click",".agree_btn",function(e){
//your code
});
do not use .live
its deprecated docs
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
Upvotes: 8
Reputation: 3103
Use live()
inside common js file. for eg
$('selector').click(function(){
//function body
})
instead of this use
$('selector').live('click', function(){
//function body
})
Upvotes: 0