ngplayground
ngplayground

Reputation: 21627

Counting list elements from ajax response

jQuery

$.ajax({
    url : "/assets/inc/list.php",
    success : function (data) {
        console.log($(data).filter('li').size());
    }
});

Using the above I have tried the total number of list items in that php as the response puts back a list of

<li>

with content inside them

but I get a console.log error of

Error: Syntax error, unrecognized expression:

which has my list echoed afterwards.

example of data

<li>
    <strong>Company Name</strong>
    123 Fake Street<br />
    Fakesville<br />
    <a href="#">Link</a>
</li>
<li>
    <strong>Company Name</strong>
    123 Fake Street<br />
    Fakesville<br />
    <a href="#">Link</a>
</li>
<li>
    <strong>Company Name</strong>
    123 Fake Street<br />
    Fakesville<br />
    <a href="#">Link</a>
</li>
<li>
    <strong>Company Name</strong>
    123 Fake Street<br />
    Fakesville<br />
    <a href="#">Link</a>
</li>
<li>
    <strong>Company Name</strong>
    123 Fake Street<br />
    Fakesville<br />
    <a href="#">Link</a>
</li>

Upvotes: 2

Views: 7896

Answers (3)

Codegiant
Codegiant

Reputation: 2150

Try this

JS CODE

$.ajax({
    url : "/assets/inc/list.php",
    success : function (data) {
        console.log($(data).find('li').length);
    }
});

Upvotes: 0

Hary
Hary

Reputation: 5818

You can use this. This takes the data and only counts the line items within it. Here is the doc

$.ajax({
    url : "/assets/inc/list.php",
    success : function (data) {
        console.log($(data).find('li').length);
    }
});

Upvotes: 4

bikeshedder
bikeshedder

Reputation: 7487

The "Syntax error" comes from the $(data) part which means that data contains malformed markup code. You need to fix this at the server side.

Upvotes: 0

Related Questions