Can this be done quickly in jQuery before I start looping through them? Or would I need to also setup a separate group in the response of data with the total count as lets say.. the first variable?
The common response looks something like this:
[
{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
,{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
]
But would I use jQuery to return 2 as the total count (before I loop through them all?) Or would I need to do something like this?
[
{"total":"2"}
,{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
,{"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}
]
Whats the most efficient/common (optimization-wise) way of doing this?
As after json decoding you are getting an array of objects(from what you have posted). You can always access the length property of that to get total count.
As you have got this array, I assume you have been able to parse the json response into a JS object. You can use dataType: 'json' to tell jQuery to do that automatically for you or you can parse that yourself using jQuery.parseJSON() but that is necessary if you set dataType:'json' or set content-Type header to application/json from server.
So you can do something like this
$.ajax({
....
dataType: 'json',
success(function(data){
if(data){
var total = data.length;
}
}
});
So you dont need to send the total count back from server. You can get that with JS after getting the response and that will make it easier for you traverse that response using $.each as the whole array contains same type of objects (doesn't have any special {"total":"2"} member).
Note: The length property is Pure vanilla JS, it has nothing to do with jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With