Reputation: 41
Hello guys need some help. I have a ajax code like this.
$(document).ready(function() {
$(".ajaxLoadPage").click(function(){
var page=$(this).attr('id');
alert(page);
$.ajax({
type:'GET',
url:"/SMS/jsp/"+page+".do",
async:false,
dataType:"html",
cache:false,
success:function(result){
$('#main-content').html(result);
}
});
});
}),
which is successfully returning the 'result' from the server, but when I'm trying to overwrite the div #main-content
with result like
$('#main-content').html(result);
for a few fraction of second the div#main-content
is get replaced/overwrite with 'result' but after this the div#main-content
is automatically loading the previous/old content?
Please help me I'm exactly getting why this error is occurring.
Upvotes: 0
Views: 137
Reputation: 41
The fallowing comment has helped me to solve my issue
(If .ajaxLoadPage is an <a>, then yes. That, or something like href="#")
Given by @Tomalak
Upvotes: 0
Reputation: 943217
You've said:
async:false
Which means the JavaScript will block everything else that is happening on the page.
for a few fraction of second the div#main-content is get replaced/overwrite with 'result' but after this the div#main-content is automatically loading the previous/old content?
That means that you are triggering the JavaScript by doing something that naturally loads a new page. Probably clicking on a link or submitting a form.
If you didn't have async:false
, it would have just reloaded the page without waiting for the JS to run.
To fix this properly:
Write quality HTML and enhance it with JavaScript.
Set up the link that triggers the JS so it does the right thing when JS fails. (NB: You should get this to return a complete HTML document).
<a href="/SMS/jsp/something.do">...</a>
Then you can use the href in the JavaScript.
url: $(this).attr('href'),
Make sure you prevent the default behaviour of the link when JS is available:
$(".ajaxLoadPage").click(function(event){
event.preventDefault();
You'll need to adapt $('#main-content').html(result);
so it filters out the content you aren't updating (such as main navigation).
And don't block the browser from getting on with other stuff while waiting for the data from the server (remove async:false,
).
Upvotes: 1
Reputation: 338158
There is a jQuery function specifically for this use case. It's called .load()
(docs).
$(function() {
$(".ajaxLoadPage").click(function () {
$('#main-content').load("/SMS/jsp/" + this.id + ".do");
});
});
Even if you don't want to use this function, your approach is still more complicated than it has to be:
$(function() {
$(".ajaxLoadPage").click(function () {
$.get("/SMS/jsp/" + this.id + ".do").done(function (result) {
$('#main-content').html(result);
});
});
});
Notes:
$.ajax()
when $.get()
does the job just as well.$(this).attr('id')
is a very verbose way of saying this.id
.Upvotes: 0