2

I have an array in php file test.php; I need it in Javascript array.

<?php 
$phpArray = glob('*.jpg');
echo json_encode($phpArray);
?>

I need each filename in Javascript array so I can access it like:

myJavasciptArray[0];

I need to get my JavaScript array loaded from the function:

$("#button2").click(function(){
$.get("test.php",function(data){
var mypics=data;
  alert(mypics[1]);      
});
});

but what I get instead of each filename in the array is a character.

myJavasciptArray[0]="["

instead of:

myJavasciptArray[0]="myfile1.jpg"

4 Answers 4

1

instead of using jQuery.get(), use jQuery.getJson() and you should be fine. If you don't, myJavascriptArray is a string, and someString[0] means the first letter of the string.

0

You are not getting result as JSON type.

Add json dataType to your $.get() so result is parsed as JSON:

$("#button2").click(function(){
   $.get("test.php",function(data){
      var mypics=data;
      alert(mypics[1]);      
   }, 'json');
});
0

Try JSON.parse here :

$.get("test.php",function(data){
    var mypics = JSON.parse(data);
    alert(mypics[1]);      
});
0

What you getting is a string back from the request, you will need to use JSON.parse() function to get the correct json object

var mypics = JSON.parse(data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.