Home    Articles

 

How to make simple POST ajax call with jquery

 

If you need a simple ajax call to a php file or URL using jQuery, here is a simple example:

<html>
	<head>
		<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
		<script>
			$( document ).ready(function() 
			{

				$.post('http://www.your-website.com/my_ajax_response_file.php', { name: "John", time: "2pm" }, function(theResponse)
				{
					$("#result").html(theResponse);
				}); 															
				
			});
		</script>
	</head>
	<body>
		<div id="result">
			
		</div>
	</body>
</html>

This example will call an URL ( or file ) located on your server in order to get the echoed data displayed by the file my_ajax_response_file.php .

This file must be standalone from your website in order to get clean data. This means that no <head> html tag must be displayed by your php code.

Also add an exit; line to the end of the file.

You can include any file you want, the most inportant thing is to be careful what you display with this file becouse the jQuery function will add the result into your div with id="result". 

The my_ajax_response_file.php can contain an simple echo, like this:

<?php
 echo 'These words are returned by the ajax call';
 exit;
?>

 

by