views:

59

answers:

5

I have a simple $.ajax call that returns a response that looks like this:

<div id='type'>success</div>
<div id="graph"></div>
<script type='text/javascript'>
   //some script that manipulates the graph div
</script>

and on my .ajax's success(response) function, I have:

$(response).find('#type').text()

my problem is that it always returns null if I use .html()

and 'an empty string' when i use .text();

Is there something wrong with my syntax?

A: 

It cant be something as simple as the single quotes around the id in the type div can it?

(the html, not the js)

Iain
Single or double quotes are interchangeable here, as long as they're matched :)
Nick Craver
A: 

In your $.ajax() request, set dataType as html

Zlatev
+3  A: 

Your response HTML needs to have a root element so that it can find() elements, because find() searches descendants of a DOM element. You can achieve this by adding the response to the document's DOM, or to another jQuery DOM element.

You can also do this and it'll work as well:

$('<div>' + response + '</div>').find('#type').text();
BoltClock
+1 because it also answers the question
lock
+7  A: 

It's because it's at the root level of the response, so .find() won't work (because it's not a child), you need .filter(), like this:

$(response).filter('#type').text()
Nick Craver
thanks for the quick response
lock
@lock - welcome :)
Nick Craver
+1  A: 

here you can test your code should work fine. you have to have a problem in ajax, try with "alert" to "response" to see what response you get

test

andres descalzo
It's worth noting that this test isn't valid, doing a `.find()` on a document fragment created from an AJAX response is *very* different than doing a `document.getElementById()` already *in* the DOM.
Nick Craver
Is very very very different?, In the case of putting the response into a div,var newres = $ ('<div>' + response + '</ div >');work well, I understand your explanation, but not so strictly applied in this case.
andres descalzo