Jump to content

Passing a Javascript var into a php echo


Scavenger

Recommended Posts

Hey guys,

 

This seems rather simple but as I'm new to php I cannot solve it and have been unable to find a solution anywhere. What I'm trying to do is echo back a value from a php array using a javascript function. But that value is of a specific index in the array which is represented by 'value'. What is the proper way to right this php part?

http://www.simplemachines.org/about/copyright.php

SMF © 2006, Simple Machines LLC

<script>
function myFunction(value) {
  alert ("<?php echo $myArr[value][0]["name"] ?>");
}
</script>

 

On a side note, if I replace [value] with 0 the alert returns the value I am looking for so I suspect that there is a way to make this work.

 

Thanks,

Scav

Link to comment
https://forums.phpfreaks.com/topic/86735-passing-a-javascript-var-into-a-php-echo/
Share on other sites

PHP is server side, javascript is client side, you need to get value back to the server.

Most commonly accomplished by a form submitting to itself.

 

or

 

silently send a form via a hidden inline frame and then get the results with javascript in the parent page.

 

I thought I would avoid recreating the array in javascript. There must be a way to make this work.

 

If  alert ("<?php echo $myArr[0][0]["name"] ?>"); returns a value then can't it be adapted to something like alert ("<?php echo $myArr['+value+'][0]["name"] ?>"); .Obviously the latter doesn't work, but  there must be a proper way to write this. 

$javascript = <<<HTML
<script>
function myFunction(value) {
 alert ("{$myArr[value][0]["name"]}");
}
</script>
HTML;

 

Edit:The forum likes to mess up things I put in php/code tags, but you get what I mean.

 

...something along these lines may work, you might need to play around with it a little. On a system I'm currently working on I have an include for the header, inside the include I have something like:

 

<script type="text/javascript">
/* <![CDATA[ */
<?php if(isset($page_js) echo $page_js; ?>
/* ]]> */
</script>

 

Then on my pages, before the header if I want the page to have some Javascript (just for that one page) I just do...

 

<?php
$page_js = <<<HTML
$(document).ready(function() {
$('a').focus(function() { this.blur(); } );
});
HTML;
?>

 

That works for me, perhaps now you will be able to get whatever you are attempting to work.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.