I am new to PHP, I have following scenario; On PHP side I have a file get_folders.php
<?php
$arr = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/var z/www/scripts')) as $filename)
{
array_push($arr,$filename);
}
print (json_encode($arr));
?>
On html side I have
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function myFunction()
{
$.getJSON("get_folders.php", function(data){
alert("Data Loaded: " + data);
$('#thetable');
var html = '';
for(var i = 0; i < 10 ; i++)
html += '<tr><td>' + data;
$('#thetable').append(html);
});
}
</script>
</head>
<button onclick="myFunction()">Try it</button>
<div>
<table id="thetable">
<th>Header 1</th>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
....... I can print the array on php side and its all good. But only thing i get in alert is
Data Loaded: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
1 Answer 1
Firstly, the Javascript alert() function is pretty basic; it can only deal with string input. If you give it an object or an array, it will choke. You're giving it objects, so it is showing you that fact in the best way it can.
If you really want to see what the data variable contains, I recommend using the browser's debugging tools rather than alert(). All modern browsers have a console.log() function, which outputs your debug data to the debugging console rather than an alert box. This will give you much more useful info. Press F12 to get the debugging panel in any browser.
But my guess is that you aren't intending to output an arry of SPLFileInfo objects. It looks like you're probably intending to send an array of filenames.
The iterators you're using for the loop produce an SPLFileInfo object, not simply the filename.
To get just the filename, you would use the getFilename() method, like so:
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/var/www/scripts')) as $fileinfo)
{
array_push($arr,$fileinfo->getFilename());
}
This will now generate an array of filenames, which I think is what you want.
[object Object]. Your data is fine or at least the output is ok. The loop looks strange though.