-1

I want to call java script in my PHP file but it in not working. I am in confusion because when i combine whole code in one single php file it works fine but again when i split the codes in two pages like test.php and upload.js and when i am calling the .js file in .php it don't works.I have done various search but i am not getting what i needed. Can someone figure it where i am missing what.

here is the sample code of test.php

enter image description here here is the js function

enter image description here

majidarif
  • 18,694
  • 16
  • 88
  • 133
jabir khan
  • 21
  • 1
  • 6

2 Answers2

1

I'm not sure I follow exactly what you are trying to do, but PHP is executed server side, Javascript is executed client side.

If you have a PHP file such as:

<script>
<?php
    echo 'alert("Hi");';
?>
</script>

then the PHP is executed before anything is sent to the browser. The browser gets:

<script>
    alert("Hi");
</script>

So if you have javascript trying to call a PHP function after the page has been sent to the browser, it just won't work. Browsers can't execute PHP. You might want to look into AJAX or similar to send a request back to your server, which can then execute PHP code.

It might help if you could post all the various versions of code so we can see what you are attempting.

ttt
  • 33
  • 4
0

Separate JS files will not be able to read any PHP code. What you can do is setup all the values you need inside your PHP code so that you can access it in any separate JS file. One way to do this is to setup a global namespace/variable and hook into browser window object.

// upload.js

function callphp() {
   var result = window.MyJSValues.result;
}

// test.php
...
<?php
function php(){
   return "Welcome to Javascript"; 
}
?>

<script>
 // setup our global values into its own object
  window.MyJSValues = window.MyJSValues || {}; // initialize empty object
  window.MyJSValues.result = '<?php echo php() ?>';
</script>
<script src="upload.js"></script>
...
<button onclick="callphp()">Test</button>
...
erickb
  • 6,193
  • 4
  • 24
  • 19