1

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.

2
  • So what is in data? Commented Jan 26, 2021 at 15:14
  • There must be something wrong with my code, but I hoped, the content is actually the text inside, here "6" Commented Jan 26, 2021 at 15:14

1 Answer 1

2

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);
  }
});
Sign up to request clarification or add additional context in comments.

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.