[php] How can you use php in a javascript function

<html>
    <?php
        $num = 1;
        echo $num;
    ?>
    <input type="button"
           name="lol" 
           value="Click to increment"
           onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {
        <?php
            $num = 2;
            echo $num;
        ?>
        }
    </script>
</html>

This is what i have so far, not working though, i think i need to use ajax or something but i have no idea what to do.

Thanks

This question is related to php javascript ajax function client-side

The answer is


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.


Simply return it:

<html>
    <?php
        $num = 1;
        echo $num;
    ?>
    <input type="button"
       name="lol" 
       value="Click to increment"
       onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {
            Return <?php
            $num = 2;
            echo $num;
            ?>;
        }
    </script>
</html>

There is a way to run php in client-side javascript (not talking about server-side js here). Don't know if this is a very good idea, but you can. As some people pointed out you have to keep in mind the php is evaluated on the server and then returned as static stuff to the browser who will then run the javascript with the added data from the server.

You have to tell the server to evaluate the js files as php files, if you are running an apache server you can do this with a htaccess-file like this:

<FilesMatch "\.js$">
SetHandler application/x-httpd-php
Header set Content-type "application/javascript"
</FilesMatch>

More info here:

Parse js/css as a PHP file using htaccess

http://css-tricks.com/snippets/htaccess/use-php-inside-javascript/

Edit: On http page request this trick makes files with js extension be parsed by the php compiler. All php parts in the js file will get executed and the js file with added server data will be handed to the browser.

However, the OP uses an html formated file (probably with php extension), no js file, so in this specific case there's no need for my suggestion.

The suggested js solutions are the way to go. If the variable needs to get stored on the server, use ajax to send it there.


you use script in php..

<?php

        $num = 1;
        echo $num;

    echo '<input type="button"
           name="lol" 
           value="Click to increment"
           onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {';
            $num = 2;
            echo $num;

        echo '}
    </script>';
?>

Try this may work..

<html>
   <?php $num = 1; ?>
   <div id="Count"><?php echo $num; ?></div>
   <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
   <br>
   <script>
   function Inc() {
       i = parseInt(document.getElementById('Count').innerHTML);
       document.getElementById('Count').innerHTML = i+1;
   }
   </script>
</html>

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.


despite some comments, at some cases it's really necessary to access PHP functions at Javascript (e.g. the AJAX cases).

At these cases you can use the mwsX library to use your PHP functions at Javascript.

mwsX library: https://github.com/loureirorg/mwsx


Simply, your question sounded wrong because the JavaScript variables need to be echoed.

_x000D_
_x000D_
<?php_x000D_
        $num = 1;_x000D_
        echo $num;_x000D_
        echo "<input type='button' value='Click' onclick='readmore()' />";_x000D_
     echo "<script> function readmore() { document.write('";_x000D_
        $num = 2;_x000D_
        echo $num;_x000D_
        echo "'); } </script>";_x000D_
?>
_x000D_
_x000D_
_x000D_


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/


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to client-side

Getting query parameters from react-router hash fragment Single Page Application: advantages and disadvantages How to export JavaScript array info to csv (on client side)? Best practice for localization and globalization of strings and labels How can you use php in a javascript function How to create a file in memory for user to download, but not through server? Pass request headers in a jQuery AJAX GET call Image resizing client-side with JavaScript before upload to the server Print directly from browser without print popup window Sending emails with Javascript