开发者

Call php from javascript and return an array from php to Javascript function

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

GetF开发者_C百科ilenme.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;
?>


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); 
?>


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');
  }
});


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";
?>


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.


At the end, do this:

print json_encode($filesArray);

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


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>


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.


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜