[php] how to execute php code within javascript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
    function funk(){
        alert("asdasd");
        <?php echo "asdasda";?>
    }
</script>

When the button is pressed i want to execute php code (at this point to echo asadasda)

This question is related to php javascript

The answer is


If you do not want to include the jquery library you can simple do the following

a) ad an iframe, size 0px so it is not visible, href is blank

b) execute this within your js code function

 window.frames['iframename'].location.replace('http://....your.php');

This will execute the php script and you can for example make a database update...


If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>

However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  $('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>

This runs the php script and loads whatever message it returns into <div id="resultMsg">.

order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:

<?php
// do adding to cart stuff here
echo 'Added to cart';
?>

For this to work you will need to include jQuery on your page, by adding this in your <head> tag:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).

If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.

Why do you want to do this?


Interaction of Javascript and PHP

We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

But -- good news; it can be made to work and here's how.

The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.

First, to clarify the DHTML usage I'll cite this DHTML example:

<script type="text/javascript">

function updateContent() {
 var frameObj = document.getElementById("frameContent");
 var y = (frameObj.contentWindow || frameObj.contentDocument);

 if (y.document) y = y.document;
 y.body.style.backgroundColor="red";  // demonstration of failure to alter the display

 // create a default, simplistic alteration usinga fixed string.
 var textMsg = 'Say good night Gracy';

 y.write(textMsg);

 y.body.style.backgroundColor="#00ee00";  // visual confirmation that the updateContent() was effective

}
</script>

Assuming we have an html file with the ID="frameContent" somewhere, then we can alter the display with a simple < body onload="updateContent()" >

Golly gee; we don't need PHP to do that now do we! But that creates a structure for applying PHP provided content.

We change the webpage in question into a PHTML type to allow the server side PHP access to the content:

**foo.html becomes foo.phtml**

and we add to the top of that page. We also cause the php data to be loaded into globals for later access - - like this:

<?php
   global $msg1, $msg2, $textMsgPHP;

function getContent($filename) {
    if ($theData = file_get_contents($filename, FALSE)) {
        return "$theData";
    } else {
        echo "FAILED!";
        }
}
function returnContent($filename) {

  if ( $theData = getContent($filename) ) {
    // this works ONLY if $theData is one linear line (ie remove all \n)
    $textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
    return "$textPHP";
  } else {
    echo '<span class="ERR">Error opening source file :(\n</span>';  # $filename!\n";
  } 
}

// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 =       returnContent('dummy_frame_data.txt');
$msg2 =       returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');

?>

Now our javascripts can get to the PHP globals like this:

// by accessig the globals var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';

In the javascript, replace

var textMsg = 'Say good night Gracy';

with: // using php returnContent()

var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';

Summary:

  • the webpage to be modified MUST be a phtml or some php file
  • the first thing in that file MUST be the < ? php to get the dynamic data ?>
  • the php data MUST contain its own css styling (if content is in a frame)
  • the javascript to use the dynamic data must be in this same file
  • and we drop in/outof PHP as necessary to access the dynamic data
  • Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data

To be resolved: calling updateContent() with a filename and using it via onClick() instead of onLoad()

An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it


put your php into a hidden div and than call it with javascript

php part

<div id="mybox" style="visibility:hidden;"> some php here </div>

javascript part

var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';

now, you can do anything with myfield...


May be this way:

    <?php 
     if($_SERVER['REQUEST_METHOD']=="POST") {
       echo 'asdasda';
     }
    ?>

    <form method="post">
    <button type="submit" id="okButton">Order now</button>
</form>

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the result class.


Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work