javascriptajaxfilterjquery-selectors.post

Filtering/ using selectors on AJAX response


I'm new to javascript/ coding in general, and am stuck when it comes to filtering/ manipulating data received as an AJAX request. I have no access to the server side code. When a date is sent to the server it responds with a page of rota information. Within the response is a single div I'm interested in. I want to get only this div (id="medStaff"), which contains a table.

I have two such requests/ tables, and need to combine the results (merge the tables, and only show certain columns).

Finally, the resource I need to use is only available on our intranet - so whilst developing this I have to mock up the scenario using jquery.get and a locally saved copy of the resource, instead of jquery.post (this is my reason for not using jquery.load with the container ID, and some CSS styling to show only the parts of the table I want - which works fine locally, but not for the real application).

Presumably I should be using filter on my ajax response (since it's a top level div I'm after), then some nth-child selectors to choose my pieces of table data. I just can't get any of this to work. I want to extract the first and second columns of the table in the identified division. The table itself has no id tag. Code (for the bit I'm specifically stuck with) below:

<html>
<head>
<script src="jquery.js"></script>
</head>
<div id="div1" ></div>
<div>
<script>
$.get("Medicine%20%20AGM%20Medical%20Staff%20by%20Firm.htm", function(response) {   
    $(response).filter( '#medStaff' );
    document.getElementById("div1").innerHTML = response;
});
</script>
</div>
</form>
</html>

I would greatly appreciate any advice. Thanks, R


Solution

  • .filter() doesn't modify the variable, you need to use the result.

    $.get("Medicine%20%20AGM%20Medical%20Staff%20by%20Firm.htm", function(response) {   
        $("#div1").html($(response).filter( '#medStaff' ));
    });
    

    You can also do this more simply with .load(), which allows you to put a selector after the URL:

    $("#div1").load("Medicine%20%20AGM%20Medical%20Staff%20by%20Firm.htm #medStaff");