1. Code
  2. Coding Fundamentals

How to Call a PHP Function From JavaScript

Scroll to top

PHP comes with a lot more built-in functions to work with strings, arrays and other types of data in comparison to JavaScript. Therefore, it is natural for a lot of people to feel the urge to call PHP functions from JavaScript. However, as you might have guessed or found out, this does not work as expected.

There can be a lot of other cases where you might want to run some PHP code inside JavaScript—for example, to save some data on your server. Simply placing the PHP code inside JavaScript will not work in this case either.

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.

Whenever you want to visit a page, the browser sends a request to the server, which then processes the request and generates some output by running the PHP code. The output or generated webpage is then sent back to you. The browser usually expects the webpage to consist of HTML, CSS, and JavaScript. Any PHP that you might have placed or echoed inside JavaScript would either have run already or won't run at all when the webpage loads in the browser.

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.

Call a PHP Function From JavaScript

We can use AJAX to call a PHP function on data generated inside a browser. AJAX is used by a lot of websites to update parts of webpages without a full page reload. It can significantly improve the user experience when done properly.

Keep in mind that the PHP code will still run on the server itself. We will just provide it with data from within our script.

Using jQuery AJAX to Run PHP Code

If you are using jQuery on your website, it becomes incredibly easy to call any PHP file with code that you want to run.

You can pass one or two parameters to the ajax() function. When two parameters are passed, the first one will be the URL of the webpage where the browser will send your request. When you pass only one parameter to ajax(), the URL will be specified in the configuration.

The second parameter contains a bunch of different configuration options to specify the data you intend to process and what to do in case of success or failure, etc. The configuration options are passed in JSON format.

You can use the method parameter to specify the HTTP method which should be used for making the request. We will be setting it to POST because we will be sending data to the server as well.

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:

1
<!doctype html>
2
<html lang=en>
3
<head>
4
<meta charset=utf-8>
5
<title>PHP Function in JavaScript Demo</title>
6
<style>
7
body {
8
    font-family: 'Lato';
9
    font-weight: 400;
10
    font-size: 1.4rem;
11
}
12
13
p {
14
    text-align: center;
15
	margin-bottom: 4rem;
16
}
17
</style>
18
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
19
</head>
20
<body>
21
<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>
22
<p class="broken"></p>
23
<script>
24
$.ajax({
25
  method: "POST",
26
  url: "wrap.php",
27
  data: { text: $("p.unbroken").text() }
28
})
29
  .done(function( response ) {
30
    $("p.broken").html(response);
31
  });
32
</script>
33
</body>
34
</html>

Place the following code in a file called wrap.php in the same directory.

1
<?php
2
$text = $_POST['text'];
3
$output = wordwrap($text, 60, "<br>");
4
echo $output;
5
?>

Remember that you have to echo the data that you want to send back to the browser. Your webpage will look like the image below if everything goes well.

Calling PHP Function in JavaScript with AJAXCalling PHP Function in JavaScript with AJAXCalling PHP Function in JavaScript with AJAX

Using the Fetch API to Run PHP Code

You can also use the Fetch API to run PHP code on data collected inside the browser by sending a POST request to the server. In the previous example, we could replace the AJAX code with the following JavaScript to get the same result.

1
fetch('wrap.php', {
2
    method: 'POST',
3
    headers: {
4
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
5
    },
6
    body: "text=" + document.querySelector("p.unbroken").innerText
7
  })
8
  .then(response => response.text())
9
  .then(data => document.querySelector("p.broken").innerHTML = data);

Just like in the AJAX example, we specify the URL and provide additional header information that we will be sending our data in URL encoded form. This allows us to use $_POST on the server side to read the data.

Call a JavaScript Function From PHP

As you know by now, PHP will run before JavaScript when you request a webpage from some server. We can also output anything we want to show on the webpage using echo. The same echo can be used to output JavaScript that will run in the client's browser.

Here is some example code that will check an array of strings to find the index of the last palindrome. This index is stored in a PHP variable, which is then passed to JavaScript written inside the script tag using echo.

1
<?php
2
3
$words = ['apple', 'radar', 'mango', 'civic', 'banana'];
4
5
$pal_index = 0;
6
$last_pal = 0;
7
foreach($words as $word) {
8
  if($word == strrev($word)) {
9
    $last_pal = $pal_index;
10
  }
11
  echo '<p>'.ucfirst($word).'</p>';
12
  $pal_index += 1;
13
}
14
?>
15
<script>
16
<?php
17
echo 'let p_el = document.querySelectorAll("p")['.$last_pal.']';
18
?>
19
let red = Math.round(p_el.getBoundingClientRect().top)%256;
20
let green = Math.round(p_el.getBoundingClientRect().right)%256;
21
p_el.style.color =  "rgb(" + red + ", " + green + ", 0)";
22
</script>

The above example shows how you can pass data from PHP to JavaScript by simply echoing it. Just make sure that the code you echo is valid JavaScript.

Conclusion

We all know that PHP runs on servers and JavaScript usually runs in browsers. Since they both execute at different times, you cannot simply call functions from one language inside another and expect the code to work. However, there are ways to work around that issue, making it possible to exchange information between PHP and JavaScript.

To summarise, you can use AJAX when you want to call a PHP function from JavaScript or run PHP code on some data generated inside browsers. You can use echo in PHP to output JavaScript code which will run later in the client's browser. If you have any questions about the article, please let me know in the comments.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.