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);
});
}
});
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] == ""))
This should be enough:
if (typeof js_array === 'undefined' || !js_array.length) {
$('<p>Array is empty.</p>').appendTo(results);
} else {...}
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