I'm using Ajax in my web application, and here's my Ajax Jquery function :
$(".AlarmLink").click(function(){
alert('ok');
$(".page-content").empty();
$("#alarm-loader").css('display','block');
$.post($(this).attr("href"),
function(data){
var PageContent = $(data).find(".page-content");
$("#alarm-loader").css('display','none');
$(".page-content").append(PageContent.html());
});
return false;
});
and I call it from HTML link using the class="AlarmLink".
But the problem is that this works sometimes and sometimes not .
Try this. Probably you have elements added to page after listener is set.
$(document).ready(function(){
$(document).on('click', '.AlarmLink', function() {
alert('ok');
$(".page-content").empty();
$("#alarm-loader").css('display','block');
$.post($(this).attr("href"),
function(data){
var PageContent = $(data).find(".page-content");
$("#alarm-loader").css('display','none');
$(".page-content").append(PageContent.html());
});
return false;
})
});
A few possible problems,
e.preventDefault()
, although I see your return false does that (and e.stopPropagation()
) already. So you do not need both, just e.preventDefault();
or your return false
.on
targetting the document, then filtering by your .AlarmLink
selector (after the click occurs).Putting all this together you get:
$(function(){
$(document).on('click', ".AlarmLink", function(e){
alert('ok');
$(".page-content").empty();
$("#alarm-loader").css('display','block');
$.post($(this).attr("href"),
function(data){
var PageContent = $(data).find(".page-content");
$("#alarm-loader").css('display','none');
$(".page-content").append(PageContent.html());
});
return false;
});
});
A DOM ready handler is not required for a delegated event attached to document
as document
always exists, so you can reduce the example to:
$(document).on('click', ".AlarmLink", function(e){
alert('ok');
$(".page-content").empty();
$("#alarm-loader").css('display','block');
$.post($(this).attr("href"),
function(data){
var PageContent = $(data).find(".page-content");
$("#alarm-loader").css('display','none');
$(".page-content").append(PageContent.html());
});
return false;
});
Try this code, It will help you most probably
$(function(){
$(".AlarmLink").click(function(){
alert('ok');
$(".page-content").empty();
$("#alarm-loader").css('display','block');
$.post($(this).attr("href"),
function(data){
var PageContent = $(data).find(".page-content");
$("#alarm-loader").css('display','none');
$(".page-content").append(PageContent.html());
});
return false;
});
});
$(document).ready(function(){
$(".AlarmLink").live('click', function() {
alert('ok');
$(".page-content").empty();
$("#alarm-loader").css('display','block');
$.post($(this).attr("href"),
function(data){
var PageContent = $(data).find(".page-content");
$("#alarm-loader").css('display','none');
$(".page-content").append(PageContent.html());
});
return false;
})
});