tags:

views:

130

answers:

8

Trying to find div element with "result" id in returned from ajax call html content with no luck. Here is my code:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        result = $(response).find("#result");
        alert(response); // works as expected (returns all html)
        alert(result); // returns [object Object]
    }
});

Unfortunately, alert(result) doesn't return div#result. Any suggestions?

Thank you!

A: 

try this:

result = $("#result", response);

btw alert is a ghetto way to debug things, try console.log

antpaw
@antpaw LOL *ghetto*.
Jason McCreary
A: 

Is #result in the response HTML? Try the following. jQuery will still return an empty object if it doesn't find anything.

alert(result.length);
Jason McCreary
A: 

You should add dataType: "html" to the request. Im quite sure you wont be able to search the DOM of the returned html if it doesnt know it is html.

Fabian
A: 

You might have to do something like

var content= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d

then you should be able to use

result = $(content).find("#result")
drusnov
This will work for sure if you are using a web service, and your data type is 'json'
drusnov
+2  A: 

It seems to be working correctly. You said that it returns [object Object], which is what jQuery will return with the find("#result") method.

Try alerting an attribute of that object, like result.attr("id").

stjowa
+2  A: 

The jQuery find() is returning a jQuery object that wraps the DOM object. You should be able to work with that object to do what you'd like with the div.

Ryan
stjowa beat me to it. It looks like it's working as expected.
Ryan
A: 

Specify dataType: "html".

If you do not jQuery will guess the requested data type (check: http://api.jquery.com/jQuery.ajax/). My guess is that in your case response was a String rather than a DOMObject. Obviously DOM methods won't work on a String.

You could test that with console.log("type of response: " + typeof response) (or alert("type of response:" + typeof response), in case you don't run Firebug)

FK82
A: 

It shows [object Object) because of the jQuery wrapper. If you want to see the HTML, change it to this...

alert(result.html());
Josh Stodola