How to execute PHP code within JavaScript

Asked
Active3 hr before
Viewed126 times

8 Answers

executejavascript
90%

All hope is not lost, though. In this tutorial, I'll explain how you can call PHP functions from JavaScript and JavaScript functions from PHP.,Javascript, PHP & Python,The reason you can't simply call a PHP function from JavaScript has to do with the order in which these languages are run. PHP is a server-side language, and JavaScript is primarily a client-side language.,Curated Presentation Assets

Now, let's see an example of a basic AJAX request where we will pass data to a PHP file and call the PHP function wordwrap() within that file. Here is our complete webpage:

<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>PHP Function in JavaScript Demo</title>
<style>
body {
    font-family: 'Lato';
    font-weight: 400;
    font-size: 1.4rem;
}

p {
    text-align: center;
	margin-bottom: 4rem;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p class="unbroken">The United States (U.S. or US)—officially the United States of America (USA), commonly known as America—is a country primarily located in North America, consisting of 50 states, a federal district, five major self-governing territories, 326 reservations, and various possessions. At 3.8 million square miles (9.8 million square kilometers), it is the world's third- or fourth-largest country by total area. With a population of more than 328 million people, it is the third most populous country in the world. The national capital is Washington, D.C., and the most populous city is New York City.</p>
<p class="broken"></p>
<script>
$.ajax({
  method: "POST",
  url: "wrap.php",
  data: { text: $("p.unbroken").text() }
})
  .done(function( response ) {
    $("p.broken").html(response);
  });
</script>
</body>
</html>
load more v
88%

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:,Interaction of Javascript and PHP,put your php into a hidden div and than call it with javascript,Now our javascripts can get to the PHP globals like this:

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 ";?>");

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'; ?
>
load more v
72%

You can call PHP function through Javascript by passing the value, you need as output of PHP function as a string in Javascript.,Call PHP Function from JavaScript,Value of variables x & y is given by Javascript called by PHP function and printing the return value ‘sum of two variables’ in Javascript as output.,Call a JavaScript Function from PHP

In this example we define a variable in PHP and we are calling the variable through Javascript.

<?php
// Call PHP Script from javascript

$mydata='Variables declaration in PHP';
?>
<!doctype html>
<html>

<head>
   <meta charset="utf-8">
   <title>PHP & Javascript</title>
   <script type="text/javascript">
      alert("<?php echo $mydata?>");
   </script>
</head>

<body>
</body>

</html>
load more v
65%

Redirect the current page to a PHP script. ,Use the Fetch API to call a PHP script. ,Use AJAX to call a PHP script. ,Submit a hidden HTML form, an old-school method.

<!-- (A) HTML FORM -->
<form onsubmit="return ajaxcall();">
  <input type="text" id="name" required/>
  <input type="email" id="email" required/>
  <input type="submit" value="Save"/>
</form>

<!-- (B) JAVASCRIPT -->
<script>
function ajaxcall() {
  // (B1) GET FORM DATA
  var data = new FormData();
  data.append('name', document.getElementById("user-name").value);
  data.append('email', document.getElementById("user-email").value);
 
  // (B2) AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "0-dummy.php");
  xhr.onload = function () {
    console.log(this.response);
  };
  xhr.send(data);
  return false;
}
</script>
load more v
75%

You can use fetch() JavaScript method and send an HTTP request to the PHP server,Call the PHP function over an HTTP request using fetch() JavaScript method,You can call PHP function inline from the <script> tag,And those are the two ways you can call PHP function from JavaScript. More often, you’d want to separate the PHP files from your JavaScript files and call PHP function using HTTP requests.

< ? php

function add($x, $y) {
   return $x + $y;
} ?
>
load more v
40%

<script>
   var phpadd = < ? php echo add(1, 2); ? > //call the php add function
   var phpmult = < ? php echo mult(1, 2); ? > //call the php mult function
   var phpdivide = < ? php echo divide(1, 2); ? > //call the php divide function
</script>
22%

I have tried to directly insert php code in javascript block, but it doesn't work. What should I do? , how to execute php script in a <javascript> block? , ×   You cannot paste images directly. Upload or insert images from URL. , It looks like your confusing a PHP Hook with javascript. 

 

add_hook('ClientAreaHeadOutput', 1, function($vars) {

return <<<HTML
    <script type="text/javascript">
        $( document ).ready(function() {

        $("#someElement").click(function(){
			// How to insert php code here?????????????????????????????
			
			<?php $value = 'ttt'; ?> //This is not work, what should I do?


});

</script>
HTML;




});
load more v
60%

JavaScript is the client side scripting language and PHP is the server side scripting language. 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.,PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.,How to pass variables and data from PHP to JavaScript ?,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

load more v

Other "execute-javascript" queries related to "How to execute PHP code within JavaScript"