Click here to Skip to main content
14,640,679 members

call php function in javascript and save returning value in variable

Misbah1 asked:

Open original thread

I want to access php function from javascript. this php function returns an array. I have to save it into a variable in javascript for further processing...
Kindly help me and guide me how i do that..

php code is:

 header("content-type: application/x-javascript");

$galleryarray = array();

    function returnimages($dirname) {

        $files = array();

        $curimage = 0;

        //valid image extensions


        if($handle = opendir($dirname)) {

            while(false !== ($file = readdir($handle))) {

                if(eregi($pattern, $file)){

                  galleryarray[$curimage] =  $file';






     return $galleryarray;


    //Define array in JavaScript returnimages()
    //Output the array elements containing the image file names


html code is:

<script type="text/javascript">

            var galleryarray = returnimages();  /// ==> php function.. here i want to call php function

            var curimg = 0;

            function rotateimages(){

        var imagesDirectory =galleryarray[curimg];

                document.getElementById("slideshow").setAttribute("src", imagesDirectory)

                curimg = (curimg < galleryarray.length - 1) ? curimg + 1 : 0


            window.onload = function(){

             setInterval("rotateimages()", 900)


Tags: Javascript, HTML, PHP


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100