I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.

GetFilenme.php is another file and I am trying to access this from Config.html

PHP : Getfilename.php

<?php
$dir = 'uploads/';

$dir = $_REQUEST['dir'] ;

$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
 if ($file!='.' && $file!='..' )
 {
  $filesArray[$Counter] = $file;
  echo $filesArray[$Counter].'<br>';
  $Counter = $Counter + 1;

 }
}
return $filesArray;
?>
share|improve this question
    
I am not using Ajax... Using Pure Javascript i want to write javascript function not using Jquery.......... – NewBie Oct 20 '09 at 13:17
    
Ajax? – Jiří Pospíšil Oct 21 '09 at 9:24
    

This is assuming you download and include the jQuery javascript library:

$(function() {
    $.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
        // you should now have a json encoded PHP array
        $.each(data, function(key, val) {
            alert('index ' + key + ' points to file ' + val);
        });
    }, 'json');
});

This should be your PHP (although very insecure):

<?php
$dir = $_REQUEST['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); 
?>
share|improve this answer

Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.

For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).

new Ajax.Request('/validate.php', {
  method: 'get',
  onSuccess: function(transport) {
    var notice = $('notice');
    if (transport.responseText == 'true')
      notice.update('Validation successful');
    else
      notice.update('Validation failed');
  }
});
share|improve this answer
    
I am not using Ajax... do you have any idea how can i make it in pure Javascript – NewBie Oct 21 '09 at 9:31
1  
Ajax is just a term that describes exactly the sort of functionality that you want. It does not imply any particular framework, so you can do it with pure JavaScript but it will be more work. – Ben James Oct 21 '09 at 9:32
    
AJAX is the answer :) and read the wiki article on AJAX ( asynchronous JAVASCRIPT and XML ) – Aviatrix Oct 21 '09 at 9:35
    
i am getting ajax is undefined if i try to use it like this <script language="javascript"> function aaa() { new Ajax.Request('/ValidateLogin.php', { method: 'get', onSuccess: function(transport) { var notice = $('notice'); if (transport.responseText == 'true') alert('Validation successful'); else alert('Validation failed'); } }); } </script> – NewBie Oct 21 '09 at 9:58
    
Obviously, that means you're not using the Prototype framework (see the link in Ben James' answer). – Duroth Oct 21 '09 at 10:03
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

function CallSomePHP(username, password)
{
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }
    var url="myPhp.php";
    url = url+"?username="+username+"&password="+password;
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}

function stateChanged()
{
    if (xmlhttp.readyState==4)
    {
        alert(xmlhttp.responseText); // this will alert "true";
    }
}

myphp.php

<?
  // Get the values of username and password
  $username = $_GET['username'];
  $password = $_GET['password'];
  echo"true";
?>
share|improve this answer
    
i am trying to use this on my login page so if i access this then i also need to send two parameter to myPHP.php (Username and Password) How can i send the parameter also with CallSomePHP Method – NewBie Oct 21 '09 at 10:10
    
Check back my post. I have added parameters for username and password and the how to get the values you passed in php. Hope this helps – junmats Oct 22 '09 at 1:06

You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.

<div id="form"> 
<input type="text" id="email" /><br /> 
<button id="submit">Submit</button> 
</div> 
<div id="response"> 
</div> <!-- load jquery --> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>

// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;

  $("#submit").click(function(){
  // when the user clicks the submit button

    // get the value of email and put it in the variable we made above
    emailValue=$("#email").val();

    /* am going to send a post variable called "email" 
    * with the value of "emailValue" to a script called receiver.php
    */
    $.post('receiver.php',{email:emailValue},function(e){
     // "e" is variable that contains the echoed string
     // check if it's true or false
  if(e=="true")
  alert ("valid email");
  else
  alert("invalid email");
    });

  });

});

receiver.php

$email=$_POST['email'];

// checkMail is a fictional function that returns a bool
$valid=checkMail($email);

if($valid)
{
 // email is valid
 echo "true";
}else{
 // email is invalid
 echo "false";
}

Note: if you are not sending data to the PHP script you should use $.get instead of $.post, it's a little bit faster.

You can also use the JavaScript variable e and load its contents in the response division in your form like this

$("#response").html(e);

This would accomplish the same thing as if you used JQuery's load() function like Coder mentions below.

share|improve this answer

At the end, do this:

print json_encode($filesArray);

and it will send back a json object, which Javascript can read easily.

share|improve this answer
    
@cballou has provided a much more complete answer – MattBelanger Oct 20 '09 at 13:06

If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.

eg:

<script src="Getfilename.php" type="text/javascript"></script>

Then in your PHP, instead of:

return $filesArray;

have it write some JavaScript.

echo "var result = ".json_encode($filesArray).";";

Your $filesArray value will now be in your javascript as the variable result.

<script>alert(result)</script>
share|improve this answer

The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.

You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.

share|improve this answer

If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up. Something like the following:

function GetHttpObject() 
{
    if (typeof XMLHttpRequest != 'undefined')
        return new XMLHttpRequest();

    try 
    {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) 
    {
        try 
        {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
    }

    return false;
}
share|improve this answer

You can get it easily by ajax. Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.

p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){}    );

html:

<div id="data">
</div>

In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page.

In our php code //get the posted value into some $value and

if($value==2)
echo 'true I got 2'
else
echo 'I didnot got 2 You posted wrong value';

This will print true I got 2 in the div #data. This may not be your exact requirement but its very helpful.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.