Reputation: 2248
I am trying to load a div from another page using AJAX but it seems to load the entire page into my div. I would like to just load a specific div.
$('.overlay').on('click', function() {
var page_url = $(this).attr('href');
$.ajax({
url: page_url + ' #single_portfolio',
dataType: 'html',
success: function(data) {
$('#overlay').html(data);
}
});
return false;
});
Please let me know what I am doing wrong.
Upvotes: 0
Views: 7423
Reputation: 8457
Unfortunately, you're trying to substitute the $.ajax
call for the $.load
call. Only $.load
has the ability to load fragments of pages. From the $.load
documentation:
The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
$('#overlay').html(strLoadingBar).load(page_url + ' #single_portfolio');
// assuming you have your loading bar assigned to a string variable "strLoadingBar"
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
Upvotes: 1
Reputation: 3985
You can do that with .load()
:
$('#overlay').load(page_url + ' #single_portfolio');
If you must use $.ajax()
try this:
$.ajax({
url: page_url,
dataType: 'html',
success: function(data) {
$('#overlay').html($(data).children('#single_portfolio'));
//or $(data).filter('#single_portfolio')
}
});
Upvotes: 2
Reputation: 36491
You can use $('#overlay').load(page_url + ' #container');
instead of your $.ajax()
call
See http://api.jquery.com/load/
Upvotes: 0
Reputation: 15351
You cannot use a CSS selector in a remote document via AJAX like you're trying. The #single_portfolio
after the URL would act as a hash
(w/o the space in front). You need a URL that returns exactly what you need for your AJAX call. Alternatively, you can fetch the entire page, and do some processing in the callback function to extract the desired part.
Upvotes: 1