jqueryglobal-variablesphpjs

assigning global var to a php array accessed by jQuery post()


Im pretty new to jQuery (since a week) and don't understand why I can't assign the PHP (work.php) array to global var imgArrayThumbs. I'm calling an array of image names created by the php opendir function. When I alert(imgArrayThumbs); I'm just getting back [object Object]. Can someone help? Been trying to figure it out all day.

scripts.js

var imgArrayThumbs = '';

$.post("work.php", { task: "imgArrayThumbs" }, function(data) {
  imgArrayThumbs = data;
});

alert(imgArrayThumbs);

work.php

include_once 'scripts/functions.php';

if($_POST['task'] == 'imgArrayThumbs'){
  imageArray('source/examples/thumbs', 'imgArrayThumbs');
}
elseif ($_POST['task'] == 'imgArray'){
  imageArray('source/examples/', 'imgArray');
}

functions.php

function imageArray($dir, $arrayVar){
  $arrayName = array();

  $iNumber = 0;
  $open = opendir ($dir);
  while ($file = readdir( $open )){
    if($file == "." || $file == ".." || $file == ".DS_Store"){

    }else{ 
      $arrayName[$iNumber] = $file;
      $iNumber ++;
    }
  }
  closedir ( $open );

  for ($i = 0;$i<count($arrayName);$i++){ 
    if ($i == 0) { 
      echo "\"" . $arrayName[$i] . "\""; 
    }else{ 
      echo ",\"" . $arrayName[$i] . "\""; 
    } 
  } 
}

EDIT 01

Working version:

scripts.js:

var imgArrayThumbs = new Array();   
$.ajaxSetup({async:false});
$.ajax({
  type: 'POST',
  url: 'work.php',
  data: { task: "imgArrayThumbs" },
  success: function(data) {
    imgArrayThumbs = data;
  },
  dataType: 'json'
});

functions.php:

echo json_encode($arrayName); // without loop

Solution

  • alert() does a toString(). Since the jQuery code returns an object, alert prints the class type only, [object Object]. Instead, use something like Firebug, or built-in developer tools of IE and Chrome, and do imgArrayThumbs = data; console.log(imgArrayThumbs) then check the Console if you want to browse the contents of the object.

    Also, jQuery expects a JSON result by default, but your PHP code isn't exactly formatting it in proper JSON. A much simpler solution of encoding it in JSON, is remove your for loop at the end, and use echo json_encode($arrayName); instead.