How to use AJAX in PHP with example

  • Tech Area
  • October 5, 2023



AJAX stands for Asynchronous JavaScript and XML. AJAX is a technology that reduces the interactions between the server and client. It is a technique for creating better, faster, and more interactive web applications. The main purpose of AJAX technology is to exchange small amounts of data with server without page refresh. With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen.

JavaScript is a client side scripting language. It is executed on the client side by the web browsers that support JavaScript.

XML is the acronym for Extensible Markup Language. It is used to encode messages in both human and machine readable formats.

Files used in this tutorial:

1- index.php

2- read.php

Below are the step by step process of how to use ajax in PHP.

Step 1: Create index.php file

index.php

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<input type="text" id="text1">
<a href='#' onclick="on_click()">Click Me</a>

<script type="text/javascript">
	function on_click(){
		var val = $('#text1').val();
		$.ajax({
			url: 'read.php',
			method: 'post',
			data: 'Data='+val,
			success: function(data){
				alert(data);
			}
		});
	}
</script>

Step 2: Create read.php file

read.php

<?php
echo $_POST['Data'];
?>

Output


Subscribe us via Email

Join 10,000+ subscriber

Subscribe on YouTube