Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery and JSON array - How to check if array is empty or undefined?

I need to pass php array to jquery for some tasks. The php array is created for SESSION and then json_encoded for jquery. After that I'll store that variable to window js namespace in order to use the array in my jquery script.

if(isset($_SESSION['mySession'])){
    $json_array = json_encode($php_array);
}

<script>
    <?php echo "window.json_from_php = ".$json_array; ?>
</script>

The thing i need to do is to check whether this array exist at all/is empty/undefined before doing anything. The check clause succeeds for 'undefined' operand but not for the rest. How can I check in jquery whether array is empty or not?

This is the output of the json_encoded array after initialization, when there isn't any elements in the $php_array:

string '[""]' (length=4)

And here is the jquery:

$(function() {
        var results = $('#results');
        var js_array = window.json_from_php;
        var count = js_array.length;

        if ((typeof window.json_from_php === 'undefined') || (js_array === null) || (jQuery.isEmptyObject(js_array)) || (count === 0)) {
            $('<p>Array is empty.</p>').appendTo(results);
        }
        else {
            jQuery.each(js_array,function(key,val){
                $('<ul><li id="'+key+'">'+val+'</li></ul>').appendTo(results);                  
            });
        }
    });
like image 887
art2 Avatar asked Nov 14 '12 15:11

art2


2 Answers

This is how I check for an empty/null json array.

if (js_array == undefined || js_array == null || js_array.length == 0){
    $('<p>Array is empty.</p>').appendTo(results);
}

If your json array is [""] then you may need to add something like

if (js_array == undefined || js_array == null || js_array.length == 0 || (js_array.length == 1 && js_array[0] == ""))
like image 83
JoeFletch Avatar answered Sep 23 '22 20:09

JoeFletch


This should be enough:

if (typeof js_array === 'undefined' || !js_array.length) {
   $('<p>Array is empty.</p>').appendTo(results);
} else {...}
like image 29
A. Wolff Avatar answered Sep 21 '22 20:09

A. Wolff