views:

44

answers:

3

I am calling pages via AJAX in jQuery.

The content of these pages needs to be filtered so that i only grab a certain DIV class. In this instance 'Section1'.

This filtered data needs to replace the same data on the current page in the DIV of the same class.

I currently have this but it is not really working for me:

$("#dialog_select").live('change', function() {

    //set the select value
    var $optionVal = $(this).val();

    //$(this).log($optionVal);

    $.ajax({
        type: "GET",
        url: $optionVal,
        dataType: "html",
        cache: false,
        success: function(data) {

            var $filteredData = $(data).filter('.Section1');

            $('.Section1').replaceWith($filteredData);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });

});
A: 

Should

    var $filteredData

not be

    var filteredData

?

André van Toly
Don't think so. I thought it was common practice to declare variables like this in jQuery.
RyanP13
@Ryan - You are right. It is common to give the first character of a variable name `$` when it references a jQuery object. `$` is a valid character.
patrick dw
+1  A: 

I think your problem is likely here:

var $filteredData = $(data).find('.Section1');
$('.Section1').replaceWith($filteredData);

.filter() would only find top level elements in the response (if it's a page, that's <html>, and wouldn't have any results). .find() looks for decendant elements. Also keep in mind that if you have multiple .Section1 elements, this won't behave as expected and will have some duplication going on.

Nick Craver
A: 

This is a tricky thing to do and I would recommend placing the data into something like a DOMParser or document.implementation.createDocument or MSXML.

if (window.DOMParser) {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(text,"text/xml");
}
else {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(text); 
}

is a basic code example. jQuery itself can filter on a selector with the load function. http://api.jquery.com/load/ This however has several limitations such as not being able to filter on html, head, or body tags. This is why the above method is safer.

lark
He's not trying to filter on any of those elements, just the standard inside-the-`<body>` filter...seems like this is over-complication, at least to me.
Nick Craver
Agreed.Tried your suggestion Nick and it works really well.Always greatful for otehr points of view though :)
RyanP13
Nick the only problem is if the content coming back is a full HTML page. All the elements in the <head> and <body> will be on the same level and it can cause some massive confusion and incur unintended results. My answer wasn't given for simplicity. In this case your answer is fine.
lark