Jump to content


Photo

PHP variable into javascript


  • Please log in to reply
6 replies to this topic

#1 idy

idy
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 13 September 2006 - 10:11 AM

Hello !

I have the following JS function

function test(id) {
var result = '<? echo $array[' + id + ']; ?>';
alert(result);
}

which does not send anything. How is it possible to send the javascript variable id to the PHP variable (array) $array ?

Thanks a lot.

#2 Gruzin

Gruzin
  • Members
  • PipPipPip
  • Advanced Member
  • 448 posts
  • LocationGeorgia

Posted 13 September 2006 - 10:17 AM

$array[' + id + '];
What's this meant to be?
I don't need your script, I'll try to write it myself

#3 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 13 September 2006 - 10:19 AM

you are mixing js and php there buddy!

PHP will stop running once the page has been served to the client - php can do no more after that until the next request is sent.

you wil have to populate and array explicitly in js usign the php array you have constructed and then use id to traverse it.
follow me on twitter @PHPsycho

#4 idy

idy
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 13 September 2006 - 10:23 AM

OK thanks a lot.

#5 Gruzin

Gruzin
  • Members
  • PipPipPip
  • Advanced Member
  • 448 posts
  • LocationGeorgia

Posted 13 September 2006 - 10:29 AM

You could use this to get the point:

<?php
$id = "5"; 
echo "<a href='#' onClick=\"alert ('$id');\">Get it</a>";
?>

I don't need your script, I'll try to write it myself

#6 idy

idy
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 13 September 2006 - 10:39 AM

Actually the variable $array is already used in my PHP script before writing the JS function.
If I write :
var result = '<? echo $array[0]; ?>';
I do have the content of $array[0] into result.
The only thing I am trying to do is to retrieve the JS variable id instead of the hard-coded value 0 into $array. Or is still the same problem ? Thanks !

#7 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 13 September 2006 - 11:01 AM

For that you need to look at AJAX.

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users