I am making an AJAX request to a .aspx script & it returns HTML. I am having trouble parsing the returned HTML in JQuery, like I cannot access certain HTML element values or innerHTML.
Can you tell me what I am doing wrong & how I can fix it?
I call a script test.aspx & it returns just this(absolutely nothing else):
<input type="hidden" id="clientIndex" value="4"></input>
<div id="clientContent"> ...some html </div>
When I go to parse this HTML I am unable to access the inputs value or the divs innerHTML BUT I can access the input & div objects fine(they exist).
The code I use is:
$.ajax(
{
type: "POST",
url: "test.aspx",
data: "i=" + $(".clientIndexClass:first").val(),
dataType: "html"
}).done(function (msg) {
// NOTE: msg has the correct html so its sending back the right formatted HTML
var index = $(msg).find("#clientIndex").val();
var content = $(msg).find("#clientContent").html();
// ERROR HERE: content is null & index is undefined when it shd be text for both
console.log("AJAX Response: " + index + ", " + content + ", " + msg);
$(treadmill).html($(treadmill).html() + content);
if (index == "-1") {
console.log("killing intervals coz = -1");
clearInterval(ele.ajaxInterval);
clearInterval(ele.slideshowInterval);
}
});
In the above code I can find the objects with the ids ‘clientIndex’ & ‘clientContent’ using $(msg).find(“#clientIndex”); BUT I cannot access clientIndex’s value? Ie, $(msg).find(“#clientIndex”).val(); returns null????
I’m pretty sure you can’t find these objects like that.
.find()will still return a jQuery object, but I’m pretty sure you’ll find that its length is 0 because no elements were found.The problem is that
.find()looks for a match in the descendants of the selected elements. In your case you have exactly two “top-level” elements with no descendants. The solution is to use the.filter()method instead:Note: I’m storing the result of
$(msg)in a variable called$msgto save parsing the same thing two lines in a row.