Curtis Chong
Curtis Chong

Reputation: 811

How to read value of an array that has been sent from a php script

Okay so I have a txt file.

I turn the data of the txt file into an array.

$lines = file($filename);

Then send the data back to the client ($filename is determined through ajax)

print_r( array_values( $lines ));

I retrieve the data from ajax

    success: function(docinfo){
        alert(docinfo);
    }

And I get something like this:

Array
(
    [0] => 10
    [1] => 123
    [2] => 455
    [3] => 325
    [4] => 33
    [5] => 3
)

but when I want to access the values of the array

console.log(docinfo[0]);//which represents the first line of my txt file

I get "A" which is the first letter of "Array". not the value of docinfo[0] which I want.

Is there a way where I can send the array and retrieve the values so I can use them the way I want?

Upvotes: 1

Views: 49

Answers (2)

Daymon Schroeder
Daymon Schroeder

Reputation: 682

Javascript doesn't understand PHP's object format, you need to convert PHP's object into a form that a javascript parser can understand. We call that serializing, and javascript's format is called JSON.

<?php
echo json_encode(array_values($lines));
?>

this will give you something like:

  [
    1,2,3,4,5
  ]

Then you can change your onsuccess function to parse the JSON that PHP sent back:

success: function(docinfo){
    infoparsed = JSON.parse(docinfo)
    alert(docinfo[0]);
}

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Did you tried printing the array with json_encode() ?

echo json_encode(array_values($lines));

Upvotes: 2

Related Questions