Just echo the javascript out inside the if function

 <form name="testForm" id="testForm"  method="POST"  >
     <input type="submit" name="btn" value="submit" autofocus  onclick="return true;"/>
 </form>
 <?php
    if(isset($_POST['btn'])){
        echo "
            <script type=\"text/javascript\">
            var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
            </script>
        ";
     }
  ?>
Answer from keto23 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-run-javascript-from-php
How to run JavaScript from PHP? - GeeksforGeeks
July 11, 2025 - JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code. Example 1: Write JavaScript ...
🌐
W3Schools
w3schools.com › js › js_ajax_php.asp
AJAX PHP Example
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Coursesweb
coursesweb.net › javascript › javascript-code-php
JavaScript code and PHP
Thus, the same web page can contain a JavaScript code for a user and other JS code for another user. - There are two ways to combine PHP with JavaScript to achieve a dynamic and personalized result: 1) By writing the entire JS script within PHP code and adding it to the web page with PHP function 'echo' (or 'print').
🌐
W3Resource
w3resource.com › phpjs › use-php-functions-in-javascript.php
php.js tutorial - Use PHP functions in JavaScript - w3resource
php.js is a JavaScript library, enables you perform high-level operations like converting a string to time or retrieving a specific date format, in JavaScript.
🌐
PHP
php.net › manual › en › v8js.examples.php
PHP: Examples - Manual
<?php $v8 = new V8Js(); /* basic.js */ $JS = <<< EOT len = print('Hello' + ' ' + 'World!' + "\\n"); len; EOT; try { var_dump($v8->executeString($JS, 'basic.js')); } catch (V8JsException $e) { var_dump($e); } ?>
🌐
Copernica BV
php-js.com
A bridge between PHP and Javascript | PHP-JS
The PHP-JS library takes care of converting your PHP variables into Javascript variables -- even when your variables are complex nested arrays or objects. All you have to do is assign the PHP variables, PHP-JS takes care of the rest.
Find elsewhere
Top answer
1 of 16
1066

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request.
 */

// In the end, you need to `echo` the result.
// All data should be run through the built-in json_encode() function.
// You can encode any value in PHP, arrays, strings, and objects as JSON.
echo json_encode(42);

index.php (or whatever the actual page is named like)

<script>
    fetch("get-data.php")
        .then((response) => {
            // Before parsing (i.e. decoding) the JSON data,
            // check for any errors.
            if(!response.ok){
                // In case of an error, throw.
                throw new Error("Something went wrong!");
            }
            // Parse the JSON data.
            return response.json();
        })
        .then((data) => {
             // This is where you handle what to do with the response.
             // Will alert: 42
             alert(data);
        })
        .catch((error) => {
             // This is where you handle errors.
        })
</script>

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

  • Using the Fetch API
  • How do I return the response from an asynchronous call?

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<div id="dom-target" style="display: none;">
    <?php
        // Again, do some operation, get the output.
        $output = "42";
        // You have to escape because the result 
        // will not be valid HTML otherwise.
        echo htmlspecialchars($output);
    ?>
</div>
<script>
    const targetDiv = document.getElementById("dom-target")
    const myData = targetDiv.textContent
</script>

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<script>
    const myData = <?= json_encode("42", JSON_HEX_TAG); ?>
</script>
2 of 16
115

I usually use data-* attributes in HTML.

<div
    class="service-container"
    data-service="<?= htmlspecialchars($myService->getValue()) ?>"
>

</div>

<script>
    $(document).ready(function() {
        $('.service-container').each(function() {
            var container = $(this);
            var service = container.data('service');

            // Var "service" now contains the value of $myService->getValue();
        });
    });
</script>

This example uses jQuery, but it can be adapted for another library or vanilla JavaScript.

You can read more about the dataset property here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

🌐
Medium
medium.com › a-journey-through-my-software-development-career › javascript-to-php-and-back-again-f3adbd0f40b0
JavaScript to PHP and back again. Setting up a PHP backend and accepting… | by Richard Quinn | A Journey Through My Software Development Career | Medium
January 31, 2021 - In the php file, we scoop up that variable in with the $_POST['runs'] line. I have then used echo to output the data from the MySQL query. This is what is picked in the success function in the JavaScript function.
🌐
Medium
medium.com › @brajagopal.tripathi › how-do-you-write-javascript-code-inside-php-2e91c9715730
How do you write JavaScript code inside PHP? | by Brajagopal Tripathi | Medium
September 14, 2023 - This can be useful for writing JavaScript code, as it allows you to format the code in a way that is more readable and maintainable. For example: ... Which method you choose to use will depend on your personal preference. The echo the statement is simpler and more straightforward, but the heredoc syntax is more readable and maintainable. ... <?php $script = <<<JS $(function() { // Get the current time and display it in an alert message.
🌐
Code Boxx
code-boxx.com › home › 5 ways to call php file from javascript (simple examples)
5 Ways To Call PHP File From Javascript (Simple Examples)
October 19, 2023 - Negative example warning – This funky way of creating a <script src="SCRIPT.PHP"> came from a dark corner of the Internet. While this works, it is also shunned in the modern-day. Just stick with using AJAX or Fetch. That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you. Javascript AJAX – A Beginner’s Tutorial – Code Boxx
Top answer
1 of 9
39

You can't run PHP code with Javascript. When the user recieves the page, the server will have evaluated and run all PHP code, and taken it out. So for example, this will work:

alert( <?php echo "\"Hello\""; ?> );

Because server will have evaluated it to this:

alert("Hello");

However, you can't perform any operations in PHP with it.

This:

function Inc()
{
<?php
$num = 2;
echo $num;
?>
}

Will simply have been evaluated to this:

function Inc()
{
    2
}

If you wan't to call a PHP script, you'll have to call a different page which returns a value from a set of parameters.

This, for example, will work:

script.php

$num = $_POST["num"];
echo $num * 2;

Javascript(jQuery) (on another page):

$.post('script.php', { num: 5 }, function(result) { 
   alert(result); 
});

This should alert 10.

Good luck!

Edit: Just incrementing a number on the page can be done easily in jQuery like this: http://jsfiddle.net/puVPc/

2 of 9
7

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

🌐
Reddit
reddit.com › r/phphelp › can you run js in php or do something similar to js?
r/PHPhelp on Reddit: Can you run JS in PHP or do something similar to JS?
October 7, 2023 -

I'm very new to PHP, and I haven't entirely understood how it works yet. I tried searching if you could run JS in PHP, but I got a no. When I searched for the other part, I got nothing. If someone could help me understand what I want to know, let me know.

🌐
Guru99
guru99.com › home › php › php vs javascript – difference between them
PHP vs JavaScript – Difference Between Them
June 28, 2024 - Example: When you hover over the menu tab on the web-page, the drop down effect is done through JavaScript. Note: JavaScript now supports server-side execution via NodeJS · PHP Object Oriented Programming (OOPs) concept Tutorial with Example
🌐
3D Bay
clouddevs.com › home › php guides › php and javascript: making the perfect blend
PHP and JavaScript: Making the Perfect Blend
July 31, 2023 - Discover the synergy of PHP and JavaScript, and how their combined forces can create dynamic and interactive web applications. Explore code samples and best practices for harnessing their potential.
🌐
DEV Community
dev.to › smoldev › php-for-javascript-developers-5ff8
PHP For JavaScript Developers - DEV Community
May 2, 2020 - The second, is the public keyword which we’re using in conjunction with PHP’s built in __construct method. This allows us to instantiate a class as though it were a function, just like we would in JavaScript. ... Continuing with the MyClass example above, you’ll notice that we’re using this in the same way that we would in JavaScript.
🌐
Delft Stack
delftstack.com › home › howto › php › php call javascript function
How to Call JavaScript Function in PHP | Delft Stack
March 11, 2025 - Another effective way to call JavaScript functions from PHP is by using AJAX (Asynchronous JavaScript and XML). AJAX allows you to send and retrieve data asynchronously without refreshing the entire web page, making it a powerful tool for dynamic web applications. <!DOCTYPE html> <html> <head> <title>AJAX Example</title> <script> function fetchData() { var xhr = new XMLHttpRequest(); xhr.open("GET", "fetch_data.php", true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("result").innerHTML = xhr.responseText; alert('Data fetched successfully!'); } }; xhr.send(); } </script> </head> <body> <button onclick="fetchData()">Fetch Data</button> <div id="result"></div> </body> </html>
🌐
Kinsta®
kinsta.com › home › resource center › blog › javascript tutorials › php vs javascript: an in-depth comparison of the two scripting languages
PHP vs JavaScript: An In-Depth Comparison of the Two Scripting Languages
October 4, 2022 - <?php $array = array( "Frodo" => "Baggins", "Sam" => "Gamgee", "Merry" => "Brandybuck", "Pippin" => "Took", ); For ease of use, you can convert PHP objects to arrays, and convert arrays to objects.
🌐
CodeConvert AI
codeconvert.ai › home › convert from php › php to javascript converter
Free PHP to JavaScript Converter - AI Code Translation | CodeConvert AI
The AI produces high-quality JavaScript code that preserves the behavior of your original PHP code and follows JavaScript conventions. It handles common patterns, data structures, and idioms for both PHP and JavaScript.
🌐
Code Institute
codeinstitute.net › blog › coding › php vs javascript: when to use
PHP vs JavaScript: When to Use - Code Institute Global
June 5, 2024 - To declare a local variable in JavaScript, the developer should use let or const (introduced in ES6), or var (pre-ES6), as omitting these keywords will make the variable global. ... In PHP, variables declared inside a function are local by default. To use a global variable inside a function, you need to explicitly declare it as global inside that function. <?php // Local variable example function localVar() { $localVariable = 'value'; // Local variable echo $localVariable; } // Global variable example $globalVariable = 'value'; // Global variable function globalVar() { global $globalVariable; // Declare global variable echo $globalVariable; } ?>