Reputation: 4353
I uses jQuery Ajax a lot to update a div in HTML pages. The ajax is included in $(document).read(...) such as the following:
$(document).ready(function() {
$('a.button').click(function() {
var url = $(this).attr('href');
$('#content').load(url);
return false;
});
});
However, after clicking the button, Ajax sometimes fails and it displays the result in the whole page, instead in the 'content' div. This happened frequently when the page is loading or refreshed. But I suppose that $(document).ready(...) would prevent this from happening. What went wrong?
Upvotes: 1
Views: 320
Reputation: 13351
try this
$(document).ready(function () {
$('a.button').click(function () {
var url = $(this).attr('href');
$.get(url, function(data) {
$('#content').html(data);
});
});
});
Upvotes: 1
Reputation: 79032
Ajax sometimes fails and it displays the result in the whole page
This suggest that the hyperlink was not selected with the selector a.button
. Make sure that the hyperlinks you want loaded via AJAX has the class name button
, like so:
<a class="button" href="...">
If you want ALL hyperlinks to load via AJAX, remove the button selector.
$(document).ready(function() {
$('a').click(function() {
... ...
});
});
If some hyperlinks are dynamically created after page load by another script, try this:
$(document).ready(function() {
$('body').on('click', 'a', function() {
... ...
});
});
Upvotes: 1