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 direct Onclick event of any PHP function.

Wrong Interpretation of Onclick Event in PHP

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

In web pages, Onclick events are handled client-side using JavaScript and other child frameworks of JavaScript. In addition, JavaScript 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, just 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 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 *