Reputation: 39
I am trying to load products number with AJAX. The code will be more complicated but to simplify the question, there is a block on the /category-one/
<div id="products-count">6</div>
Let's say, I am on any other page, home for example. I am trying to get that "6". I have tried the following but the alert is empty.
var url = '/category-one/';
$.ajax({
url: url,
success: function(data) {
var $fullContent = $('#products-count', data)
var text = $fullContent.text();
alert(text);
}
});
What is wrong with this code? Thank you for your help in advance.
Upvotes: 1
Views: 33
Reputation: 337743
The issue is that for a contextual selector to work the second argument of the jQuery object needs to be an Element or jQuery object, or a selector string (ref). Given the context of your code, I would presume data
holds HTML, not a selector.
To fix the issue you can provide data
to a jQuery object and then find()
the required element:
var url = '/category-one/';
$.ajax({
url: url,
success: function(data) {
let $data = $(data);
let $fullContent = $data.find('#products-count');
let text = $fullContent.text();
console.log(text);
}
});
Upvotes: 2