1

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?

1
  • print_r is for debug output. it's purely a string-based format, and it's NOT intended to be used for passing data around. you want json_encode(). Commented Jun 25, 2015 at 20:54

2 Answers 2

2

Did you tried printing the array with json_encode() ?

echo json_encode(array_values($lines));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.