0

Anybody knows please help!

<script type="text/javascript" language="javascript">

var a = 3;

document.write("<?php funct1('"+a+"') ?>");

</script>

<?php 
function funct1($param){
$param = preg_replace('/\s+/', ' ', $param);
echo intval($param);
}
?>

I used to pass js variable to php in the same page this way, it works, but I want that variable : ($param from a) to return it value as integer. whenever i use (int)$param or intval($param) then it returned 0. tried preg_replace to replace space, it still not solve.

Thanks for help.

Riad
  • 3,822
  • 5
  • 28
  • 39
Ze Ro
  • 1
  • 1

3 Answers3

0

You defined variable in JavaScript and want to use it in PHP to pass back to JavaScript document.write?

It's wrong. It does not work that way.

You can connect to php via ajax if you need to pass data from JavaScript to PHP. Or if you want to pass data from PHP to JavaScript you can do

<?php $data = 'hello world' ?>
<script>
var data_from_php = <?php echo json_encode($data) ?>;
alert(data_from_php);
</script>

After PHP interpreter completes execution you get:

<script>
var data_from_php = "hello world";
alert(data_from_php);
</script>

I can't explain ajax in two words you can read this answer: https://stackoverflow.com/a/6009208/1946607

Community
  • 1
  • 1
thecotne
  • 478
  • 3
  • 10
  • Please can you expand on your answer, so the OP knows the reasons why it doesn't work, and possibly an alternative way to do it? AJAX being a hint – Adi Bradfield Dec 07 '14 at 16:29
0

You can not use javascript and php like your code.

When the client request a page; first php codes interpreted after that, the interpreted codes (html texts) sent client browser with other html and javascript texts.

You have to send javascript value to another php file with ajax.

Best Regards.

EngineerCoder
  • 1,445
  • 15
  • 30
0

You simply cannot do anything with the Javascript variable in PHP. Simply try to add 1 and return the result and you will get 0. Even if you return $param you will see there is:( press Ctrl+U )

var a = 3;

document.write(""+a+"");

which return the value itself and no PHP code took place! You need to call via ajax

Riad
  • 3,822
  • 5
  • 28
  • 39