PeterK900
PeterK900

Reputation: 3

Javascript call php function and receives back results

This postprovides sample code using obtaining a server file list as an example. Here is the code I have used:

<html lang="en-US">
<head>
  <meta charset="UTF-8">
    <title>How to create form using jQuery UI</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/pepper-grinder/jquery-ui.css" media="screen" rel="stylesheet" type="text/css">  
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script>

    <script type="text/javascript">
    $(function() {
    $.get('getfilename.php', { dir : '/ajax1/' }, function(data) {
        // you should now have a json encoded PHP array

        $.each(data, function(key, val) {
            alert('index ' + key + ' points to file ' + val);

        });
    }, 'json');
    alert ("ok");
});

    </script>
</head>
<body>
<h1>Get file names... </h1>
</body>
</html>

getfilename.php

$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;

$filesArray = array(); 
$Counter = 0; 
$files = scandir($dir); 

foreach ($files as &$file) { 
    if ($file!='.' && $file!='..' ) { 
        $filesArray[$Counter] = $file; 
        echo $filesArray[$Counter].''; 
        $Counter++;
    }
} 

echo json_encode($filesArray);

My problem is that the javascript alert alert('index ' + key + ' points to file ' + val); fails to display anything on the page. The script is working because I get a response in the Firebug console log.

ajax.jsajax.phpindex.html["ajax.js","ajax.php","index.html"]

What I need to change on the script to return this information to the html page so that I can use the JSON for further processing ?

Thanks.

Upvotes: 0

Views: 69

Answers (1)

skobaljic
skobaljic

Reputation: 9614

With your debug you broke the JSON output in PHP. So, remove:

echo $filesArray[$Counter].''; 

Also, before any output, you should add JSON header:

header('Content-Type: application/json');

At the end, your PHP file should look like this:

$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;

$filesArray = array(); 
$files = scandir($dir); 

foreach ($files as &$file) { 
    if ($file!='.' && $file!='..' ) { 
        $filesArray[] = $file; 
    }
}
header('Content-Type: application/json');
echo json_encode($filesArray);

Upvotes: 1

Related Questions