0

How can I echo a php array to the jquery $.each function?

Here's what I tried so far in php...

                  $index = 0;

                  while(!feof($file))
                  {
                     $singleLine = fgets($file);
                     $totalLines[$index] = $singleLine;

                     ++$index;
                  }
                  echo $totalLines;

Here's how I'm reading it back in jquery...

       $.post("sendFile.php",{fileName: sendFileName}, function(data)
       {
              $.each(data, function(index, value)
              {
                        alert(value);
              });
       });

The output is giving me Array...when it should be giving me Test1, Test2, Test3 for each array element...

2
  • try $.ajax and send data by json and also get by the json i think that will work for you Commented Sep 6, 2012 at 3:23
  • @mayank-swami - $.post just wraps around $.ajax, so $.post is fine. It just needs a fourth parameter, the format. Eg: $.post('file.php', {field:value}, function(data){..}, 'json'); Then it'll be parsed back as JSON Commented Sep 6, 2012 at 3:30

1 Answer 1

2

Use json_encode to encode your data.

echo json_encode($totalLines);

And your php code could simply be written as below: (use file function to read entire file into an array)

echo json_encode(file($file));
// or if need to skip the empty line and new line char
echo json_encode(file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
Sign up to request clarification or add additional context in comments.

1 Comment

not sure why but json solved my problem, thanks for the solution.

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.