How to Set Onclick Function in PHP

Onclick event is one of the most used events in any user interface. As all events on the website are related to UI, and PHP is a back-end language. So, we can not set the direct Onclick event of any PHP function.

Wrong Interpretation of Onclick Event in PHP

PHP is a popular open-source backend programming language. In addition to that, PHP handles server-side client requests and database connections. PHP has nothing to relate to the user side, on-screen interaction. So, we can not set an on click event of client-side javascript with a PHP function.

<?php
function my_funciton(){
	//do something
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Incorrect Concept of Onclick Event</title>
</head>
<body>
	<button onclick="my_funciton()">Click Me</button>
</body>
</html>

Explanation

The given above code is an entirely wrong concept of the Onclick event in PHP. We can not call a back-end function directly via any event in a front-end scripting language.

Even more, the above code will throw “Uncaught ReferenceError: my_funciton is not defined” error in the console.

Read Also: How to Open a Link On Button Click JavaScript

Correct Way to Call PHP Function via on Click Event using AJAX

In web pages, Onclick events are handled client-side using JavaScript and other child frameworks of JavaScript. JavaScript also provides the Ajax feature to communicate with the server on a specified path, which helps achieve our goal.

Note: We can call a specific PHP file via Ajax request; we can not call a particular PHP function via Ajax request. To call a PHP file Onclick event, analyze the below steps.

Step 1: Create an Onclick Event and Set an Ajax Request

<!DOCTYPE html>
<html>
<head>
	<title>Onclick event to call Ajax</title>
</head>
<body>
<button onclick="my_function()">Click Me</button>
<script>
function my_function() {
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      alert(this.responseText);
    }
  };
  request.open("GET", "ajax_request.php", true);
  request.send();
}
</script>
</body>
</html>

Explanation

In the above HTML file, we created a simple button and set an ajax request to ajax_request.php file Onclick event.

Step 2: Create a PHP File for Ajax Request

Create a PHP file and name it ajax_request.php

<?php
	echo "You called a PHP file Onclick event";
?>

Explanation

In the above PHP file, we can process any back-end procedure to achieve our desired output and return it to the Ajax client.

Conclusion

I hope now you have a complete understanding of the Onclick event via JavaScript and how to make an Ajax request to call a PHP file.

Keep Developing πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *