Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm having some difficulties in passing an array item from PHP to a Javascript function.

I have a txt file which is something like this:

recipe1 flour milk
recipe2 egg milk
recipe3 flour salt

I read txt file and need to list all recipes in a list:

recipe1
recipe2
recipe3

When a user clicks on any recipe the corresponding ingredients will be shown in a textarea.

In my example I will display in textarea

flour milk 

if users click on recipe1,

egg milk

if users click on recipe2, etc.

So here's my code:

This is the JavaScript which will populate the textarea with the text I will pass to it.

<script language="javascript" type="text/javascript">
function addtext(text){
document.testForm.cmd.value +=text;
}
</script>

Here's the code which reads line by line the txt file and put

recipe1, recipe2, recipe3, etc. in an array flour milk, egg milk, flour salt, etc. in another array.

<?php

$recipe=array();
$ingredient=array();

$fp=fopen("recipes.txt", "r");
while (!feof($fp))
{
    $line=fgets($fp);

    $line=explode(' ', $line, 2);

    $recipe[]=$line[0];
    $ingredient[]=$line[1];

}
fclose($fp);

//Print elements
$i=0;
foreach ($recipe as $rec) {

echo '<a href="#" onclick="addtext(\''.$ingredient[$i].'\'); return false">' . $rec . '</a><br />';

$i++;

}


?>

Recipe list works correclty, I cannot pass $ingredient[$i] to Javascript addtext function. I've tried without success using:

$value = echo json_encode($ingredient[$i])

Any help is appreaciated,

Thanks in advance.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

I prefer to json_encode() the entire array and pass it along to JavaScript. Here's a very rudimentary example:

<?php

$fruits = array(
  'cherry',
  'grape',
  'orange',
);

print '<script>var fruits = ' . json_encode($fruits) . ';</script>';

Then in Javascript:

console.log(fruits);

will show you what you have to work with, namely:

["cherry", "grape", "orange"] 

thus fruits[1] returns grape.

share|improve this answer

Generally you should render the <script> contents, for example, like this (just the idea, not the exact code):

echo '<script language="">
      var value = ' . json_encode($ingredient[$i]) . 
      '</script>';
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.