Javascript required
Skip to content Skip to sidebar Skip to footer

How to Call Php Function From Javascript Using Ajax

Read Time: 6 mins Languages:

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:

<!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>

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

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

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 AJAX Calling PHP Function in JavaScript with AJAX Calling 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.

fetch('wrap.php', {     method: 'POST',     headers: {       'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'     },     body: "text=" + document.querySelector("p.unbroken").innerText   })   .then(response => response.text())   .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.

<?php  $words = ['apple', 'radar', 'mango', 'civic', 'banana'];  $pal_index = 0; $last_pal = 0; foreach($words as $word) {   if($word == strrev($word)) {     $last_pal = $pal_index;   }   echo '<p>'.ucfirst($word).'</p>';   $pal_index += 1; } ?> <script> <?php echo 'let p_el = document.querySelectorAll("p")['.$last_pal.']'; ?> let red = Math.round(p_el.getBoundingClientRect().top)%256; let green = Math.round(p_el.getBoundingClientRect().right)%256; p_el.style.color =  "rgb(" + red + ", " + green + ", 0)"; </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.

How to Call Php Function From Javascript Using Ajax

Source: https://code.tutsplus.com/tutorials/how-to-call-a-php-function-from-javascript--cms-36508