0

in test.php file

<html>
<head>
  <script type="text/javascript" src="java_script.js"></script>
</head>
<body>

Name: <input type="text" id="myText" value="Mickey">

<button onclick="myFunction()">Click Me</button>

</body>
</html>

in java_script.js

function myFunction() {
    var user_name = 'Hellow World';
    document.getElementById("myText").value = user_name;
}

How to use function or variable from php_test.php

in php_test.php

  <?php
      $phpVar = 'Hello World';
      echo $phpVar;
  ?>

Thank you everyone i'm not good in English, You can correct me :)

bank9597
  • 3
  • 1

2 Answers2

1

Your question seems a little unclear, but I will do my best.

PHP

PHP stands for

PHP: Hypertext Preprocessor

It has preprocessor in its name because it only runs on the server, before it is sent to the HTML page for parsing (which is done by the browser).

JavaScript

Javascript runs after the HTML page has been received by the browser. Thus, one could assume that he/she couldn't run PHP from javascript, because PHP runs before javascript. However, AJAX is a solution to this dilemma; it stands for

asynchronous JavaScript and XML

AJAX

AJAX requests can be sent to the server, from javascript, during the browsing session. In other words, the PHP code can be re-run during the browsing session, and its output can be sent straight to javascript. jQuery has some very easy-to-use methods for using AJAX in your javascript code. You need to provide the url to the PHP program to be run and an object of key/value settings.

I hoped this helped.

Community
  • 1
  • 1
clabe45
  • 2,354
  • 16
  • 27
1

clabe45's answer is good, but I thought I'd add some more information in my own words.

PHP is a server-side language. It's run by the server. It can be used for whatever you want, but it's often used to generate HTML and sometimes Javascript. The HTML and Javascript is then sent to the browser. The browser parses (reads) the HTML and displays it in the browser, and it runs the Javascript. The HTML is what you see on the page (text, images, borders, etc.). The Javascript is used to add interactivity to the page (drop-down menus, animations, popup boxes, etc.).

Since PHP runs on the server and Javascript runs in the browser (on the client), Javascript can't access variables that are in the PHP code. The Javascript doesn't know anything about the PHP, and vice versa.

The way Javascript normally talks to PHP is through AJAX. The Javascript code can send an AJAX request to the server, and the PHP code on the server can respond to that request. clabe45's answer has some more details about AJAX (and you should definitely check out jQuery's AJAX functions, and google some tutorials).

Clonkex
  • 3,373
  • 7
  • 38
  • 55