jQuery Ajax Success get returned Array Length?

27,029

Solution 1

simply try something like this

To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, FF 4+, or Safari 5+:

alert(Object.keys(response).length); 

your code

$.ajax({
    url: "items.php",
    async: false,
    type: "POST",
    dataType: "JSON",
    data: { "command" : "getItems" }
}).success(function( response ) {
    alert( response.fruits.apple );
    alert(Object.keys(response).length); 
});

REFERENCE

How to efficiently count the number of keys/properties of an object in JavaScript?

Solution 2

Looks like you're creating an associative array on the PHP side there, which pretty much comes in as an object in JavaScript. No .length property on objects.

You can "loop" over the object keys by either invoking Object.keys alongside Array.prototype.forEach or directly using a for..in loop.

That could look like

Object.keys( response ).forEach(function( key ) {
    console.log('key name: ', key);
    console.log('value: ', response[key]);
});
Share:
27,029
夏期劇場
Author by

夏期劇場

SOreadytohelp

Updated on July 30, 2020

Comments

  • 夏期劇場
    夏期劇場 almost 4 years

    I'm trying to loop the returning Array from PHP. But jQuery .length is giving me:

    'undefined'
    

    PHP:

    $items = array();
    $items["country"] = "North Korea",
    $items["fruits"] = array(
                          "apple"=>1.0,
                          "banana"=>1.2,
                          "cranberry"=>2.0,
                        );
    echo json_encode( $fruits );
    

    jQuery:

    $.ajax({
        url: "items.php",
        async: false,
        type: "POST",
        dataType: "JSON",
        data: { "command" : "getItems" }
    }).success(function( response ) {
        alert( response.fruits.apple );
        alert( response.length );
    });
    
    • Here the First Alert() is ok, by returning: "1.0".
    • Then the Second Alert() to detect length response.length is returning:
      • undefined

    Then how can i loop this Array (or) how to loop the Fruits (defined by PHP like $items["fruits"]) from jQuery end please?

  • MarkP
    MarkP almost 10 years
  • 夏期劇場
    夏期劇場 almost 10 years
    @MarkP so the solution is to use JSON.parse(response);? Now i tried but still can not.