Reputation: 2337
How can I echo a php array to the jquery $.each function?
Here's what I tried so far in php...
$index = 0;
while(!feof($file))
{
$singleLine = fgets($file);
$totalLines[$index] = $singleLine;
++$index;
}
echo $totalLines;
Here's how I'm reading it back in jquery...
$.post("sendFile.php",{fileName: sendFileName}, function(data)
{
$.each(data, function(index, value)
{
alert(value);
});
});
The output is giving me Array...when it should be giving me Test1, Test2, Test3 for each array element...
Upvotes: 0
Views: 126
Reputation: 160943
Use json_encode to encode your data.
echo json_encode($totalLines);
And your php code could simply be written as below: (use file function to read entire file into an array)
echo json_encode(file($file));
// or if need to skip the empty line and new line char
echo json_encode(file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
Upvotes: 2