Liav Hibe Liav Hibe - 5 months ago 33
jQuery Question

using variable in jQuery load, to load partial html

I want to load a partial HTML file using AJAX like the below, however the page loads completely and not just the selector. What am I doing wrong?

$(function(){
$('#post-list a').click(function(e){
var url = $(this).attr('href');
$('#ajax-div').load(url "#post");
e.preventDefault();
});
});

Answer

From the JQuery 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.

in you code:

$('#ajax-div').load(url "#post");

should be:

$('#ajax-div').load(url+" #post");

I am assuming the missing + is a typo, but the space between url and #post is important!

Comments