styler
styler

Reputation: 16501

using the $.ajax function to fetch a specific id

I'm learning how to use jQuery methods of making AJAX calls, at the moment what I would like to know is how I use the $.ajax function to return a certain elements content. I realize this can be done easily enough using .load() but would like to get the results using .ajax(). At the moment I am fetching the clicked href attribute and returning the whole pages data when I would like to just return the #container content of the page?

Sample code being used:

jQuery(document).ready(function() {
    /* Ajax load in portfolio pages */
    var ajaxLoader = $('#ajax-loader');
    var folioContainer = $('#folio-container');

    ajaxLoader.hide();

    $('div.wp-pagenavi a', 'div#content').click(function(e) {

        $.ajax({
            url : this.href,
            method : 'get',
            success : function(data){
                folioContainer.html(data);
            }
        });

        e.preventDefault();

    });

});

Upvotes: 1

Views: 1129

Answers (2)

Joshua Wooward
Joshua Wooward

Reputation: 1508

You may be better off using the load method http://api.jquery.com/load/ , read the section "Loading Page Fragments"

not sure but try:

jQuery(document).ready(function() {
    /* Ajax load in portfolio pages */
    $('#ajax-loader').hide();

    $('div.wp-pagenavi a', 'div#content').click(function(e) {
        $.load(this.href + ' #folio-container');
        e.preventDefault();
    });
});

Upvotes: 1

Jasper
Jasper

Reputation: 76003

You should be able to .filter() the response from the server to select only the data you want:

        success : function(data){
            folioContainer.html($(data).filter('#container'));
        }

Here's a jsfiddle of this solution: http://jsfiddle.net/jasper/5HSzB/

Here's an optimized version of your code:

jQuery(function($) {
    /* Ajax load in portfolio pages */
    var ajaxLoader = $('#ajax-loader').hide();

    $('.wp-pagenavi', '#content').find('a').click(function(e) {       

        $.ajax({
            url     : this.href,
            method  : 'get',
            success : function(data){
                $('#folio-container').html($(data).filter('#container'));
            }
        });

        e.preventDefault();

    });

});

Upvotes: 1

Related Questions