How to Call a PHP function from JavaScript Using ajax

If you have to write code in PHP, it will be necessary that the information found by the server is shown dynamically on the screen. This can be done by calling a PHP function from JavaScript.

This article shows how to achieve this method and how to use it properly.

How to Call a PHP function from JavaScript Using ajax

Call external PHP function from JavaScript

JavaScript is a client-side language whereas PHP is a server-side language. So this is not possible to call a PHP function from JavaScript.

But it is possible to call a PHP function using ajax. So let’s check how it works.

What’s an AJAX request?

AJAX stands for Asynchronous JavaScript and XML and it is used to make asynchronous HTTP requests (GET/POST) to send or receive data from the server without refreshing the page. It looks like this:

<button id="getPage" type="button">Make Ajax Request</button>

<script>
	(function() {
		document.getElementById("getPage").addEventListener('click', function(){
			ajaxRequest = new XMLHttpRequest();

			if (!ajaxRequest) {
			  alert('AJAX Not supported');
			  return false;
			}
			ajaxRequest.onreadystatechange = success;
			ajaxRequest.open('GET', 'result.php');
			ajaxRequest.send();
		});
		
		function success() {
			if (ajaxRequest.readyState === XMLHttpRequest.DONE) {
				if (ajaxRequest.status === 200) {
					alert(ajaxRequest.responseText);
				} else {
					alert('Something went wrong.');
				}
			}
		}
	})();
</script>

Let’s take a basic example. Suppose, you have a page and you want to call a PHP function that will print a basic sentence i.e. “Hello World!” from an external page. So how to do it?

<script>
	$.ajax({
		url:"external-page.php",    //containing a php function
		type: "get",
		dataType: 'html',
		success:function(result){
			alert(result);
		}
	});
</script>

Here I am using jQuery to get the result from external-page.php. The external-page.php contains a basic PHP function like below.

<?php
	function helloWorld(){
		return "Hello World!";
	}
	
	echo helloWorld();
?>

So the conclusion is you can’t call PHP function from JavaScript without ajax. But using ajax, you can call an external page that has a PHP function and you can also show the return value of that function via JavaScript.

Call PHP function from JavaScript with parameters

Sometimes you need to pass parameters to a PHP function. But here we have to use Ajax again.

We can pass our parameters using GET/POST methods. Let’s check an example.

<script>
	$.ajax({
		url:"external-page.php",    //containing a php function
		type: "POST",
		dataType: 'html',
		data: {fno: 10, sno: 20},
		success:function(result){
			alert(result);
		}
	});
</script>

Here we have passes two parameters i.e. fno and sno. In our PHP function, it will be added and show the result.

<?php
	function addTwoNo(){
		$first_no = $_POST['fno'];
		$sec_no = $_POST['sno'];
		return $first_no + $sec_no;
	}
	
	echo addTwoNo();
?>

After refreshing the page, you will get 20.

Call PHP function from the same page using JavaScript

Suppose you need to show the current server date when a user clicks on a button. So let’s check the code.

<button id="getDate" type="button">Get Date</button>

<script>
	$(document).ready(function(){
		var server_date = "<?php echo date('d/m/y');?>";
		$("#getDate").click(function(){
			alert(server_date);
		});
	});
</script>

In the above code, I have called the PHP date() function to show the current date and store the value into the JavaScript variable server_date.

When a user clicks on “Get Date” button, it will show the PHP-generated current date.

Final Word

This blog post has introduced you to the basics of how to call a PHP function from JavaScript using Ajax. It’s time for me to wrap this up and give you some more resources on working with AJAX through other tutorials. I hope that this tutorial was helpful! If there is anything else we can do for you, please let us know. Happy coding!

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment