2

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?

5
  • also previously, the div#type was a 'p#type' but still it returns the same result as it is now. Commented Sep 6, 2010 at 0:02
  • 2
    have you inserted the response into the DOM? Commented Sep 6, 2010 at 0:04
  • did you try this $("#type", response).text() not sure though if that will work Commented Sep 6, 2010 at 0:06
  • @rob: well i did try that a while ago but its not how im supposed to do it, coz the purpose of retrieving that div's value is so that i could decide if i must insert it to the DOM or not Commented Sep 6, 2010 at 0:13
  • @Rob - You don't need do to that, $(response) creates a document fragment, which is traversable and much faster to deal with as well :) Commented Sep 6, 2010 at 0:15

5 Answers 5

9

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

$(response).filter('#type').text()
Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

1

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

2 Comments

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.
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.
0

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

(the html, not the js)

1 Comment

Single or double quotes are interchangeable here, as long as they're matched :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.