jQuery Ajax Logo

Super Simple Ajax jQuery PHP Tutorial

Here is another really super simple ajax jQuery php tutorial. This tutorial will attempt to help beginners understand the very basics of how to use Ajax to reload just a portion of your webpage instead of loading the complete page. So first what is Ajax? Ajax is an acronym which stands for Asynchronous JavaScript and XML. To put in very simple terms, it is a way for the user to request data from the server without having to reload the complete webpage. Ajax can be so smooth in displaying new changes in your webpage if done correctly. To begin, there is no one correct way to use Ajax. There are many different ways to use Ajax. Today, I will be using jQuery  ajax() function to request a PHP file.

OK. When I first started to learn Ajax and I would Google Ajax tutorial and from the results, I quickly realized that there are many different way to use Ajax. Can I say CONFUSION? Personally, i think that the jQuery ajax() function is one of the easiest to learn and use. There will be a link at the end of the tutorial for all of the source code. So you can follow along and copy the code or just download the source code.

Step 1. I am going to create a simple index.php file to markup our main webpage. Just a simple HTML 5 Document. Notice in the head of the document I am making a call to the jquery version which is hosted by jQuery. We need to make a call to the jQuery library in order to get access to the jQuery ajax function and to allow the jQuery code we write to run. You can write jQuery code but you need to either make a call to the jQuery library that is hosted on a CDN(Content Delivery Network) or download a copy of the jQuery library and place it in your website folder, usually in a folder called js or jscript. There are many different CDNs out there that host files for you to use.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Now I created a container in the body, then a H1 tag for a nice title. Next is the div which I gave an id of date-div. This is the div that will display the data from the php file that we will call in the jQuery ajax() function. So right now it is empty but will dynamically be changed upon a jQuery event. For the event, I created a button and attached an onclick function which will then call the getDateTime() function (we will create this function in the next step). Lastly, is the button which I attached the onclick event to call the getDateTime() function. So when the page loads the div will be empty so click the button and the jquery onclick event will call the getDateTime function which uses Ajax to request the PHP file that generates the current date and time in the American Central Timezone.
OK, here is the starting code for the index.php file:

<!doctype html>
<html>
    <head>
		<meta charset="utf-8" />
		<title>Super Simple Ajax jQuery PHP Tutorial</title>
		<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        </head>
    <body>
		<div id="container">
			<h1>Ajax jQuery PHP Tutorial</h1>
			What is the current time and date in Central Time Zone:<br />
				<div id="date-div">
					<!-- this is where the ajax file call wiil be displayed in web browser -->
				</div>
				<br/>
			<input type="button" class="btn-primary" value="Get Date & Time" onclick="getDateTime();" />
		</div>
	</body>
</html>

Step 2. Being a web developer and designer, I always want to make the examples look pretty cool with some css styles and not just plain white background and black text. So lets get styling! For simplicity sake, the norm would be to create a css folder and then a css file and then call the css file from the index.php file. Since this is a very simple tutorial, I am going to place the css styles in the head of the index.php file. First lets get rid of that plain white background and black text and H1:

body {
    background: #ecf0f1;
	color: #2c3e50;
}
h1 {
	color: #2c3e50;
}

Next, lets give our container a width and center it on the page along with the date-div and its styles:

#container {
    margin: 0 auto;
	width: 400px;
}
#date-div {
	width: 400px;
	height: 250px;
	border: 3px solid #2c3e50;
	margin: 0 auto;
	margin-top: 20px;
}

Lastly, lets do not forget our button and our paragraph tags. Stop The Clock! Where did the paragraph tags come from. This tags will be in the PHP file which we have yet to get to. So don’t worry. You will see them in the PHP file when we code that file. I gave the paragraph tags a class called pdate.

.pdate {
    color: #2c3e50;
	font-size: 16px;
	font-weight: bold;
	margin-left: 10px;
}
.btn-primary {
	background-color: #428bca;
	border-color: #357ebd;
	color: #fff;
	cursor: pointer;
	border-radius: 4px;
	display: inline-block;
	font-size: 16px;
	font-weight: 400;
	padding: 6px 12px;
	text-align: center;
	vertical-align: middle;
	white-space: nowrap;
}

OK. Enough styling. Lets get to this PHP file.

Step 3. Again keeping this as simple as possible, we will create a PHP file that will be using the PHP date function and with proper formatting we will display the date on one line and the time on the another line. I am calling this file: ajax.php. There is no AJAX code in this file, just PHP code so do not let the name confuse you. First I am using the PHP date_default_timezone_set function to set the timezone for the file. Next line, I am echoing out, or printing out the paragraph tags set with a class of pdate. HEY, there are those paragraph pdate tags we styled in the previous step. Then echo out a blank line for some spacing and then last line echo out the paragraph pdate tag again with the PHP date function using some different formatting to get the time. Here is a link to the PHP date function to research how to use the function and how to format it to the results you want.OK. Lets see the code now:

<?php
date_default_timezone_set('America/Chicago');
echo '<p class="pdate">The Date is ' . date("m/d/y") .' .</p>';
echo '<br/>';
echo '<p class="pdate">The Time is ' . date('g:i:s A') . ' .</p>';

That is it for the php file.

Step 4. Now it is time for the main event. Lets write our jQuery code using the ajax function to request the ajax.php file which will dynamically display the date and time in our date-div upon the user clicking the button. Again for simplicity sake, I will also placed this javascript code in the head of our index.php file. So I will show you the code and then try to explain it as beast as I can: And the survey says:

function getDateTime() {
    var request = $.ajax({
		url: "ajax.php",
		type: "GET",			
		dataType: "html"
	});

	request.done(function(msg) {
		$("#date-div").html(msg);			
	});
}

Lets break it down. We first name our function that will hold our ajax request. We call the function getDateTime(). This is the function that gets called when a user clicks the button on our index.php page. Inside the function, we create a variable called request which holds our ajax request. Then we start the jQuery ajax function, inside this function we have some parameters that we must give values to: url: this is the url for the file that we want to request, this could also be a file on another server, different folder, etc. Next is the type of request, we are using the GET request, and lastly is the dataType which will be returned as html. There are many more possible parameters. So here is a link to the jQuery Ajax function API documentation for more research. The last bit of code is when the request is done run the function msg which then displays the data from our ajax.php file and displays the date and time on the date-div. Click the button again and again and watch as just the time line will be changed inside our date-div and NOT the whole page reloading.

OK. Quick Summary. We have an index.php page which has our html 5 document code, including a date-div which will display our data, a button that will trigger our ajax function, our css styles and the jquery code that holds out ajax request. Our second file is a PHP file called ajax.php which uses the php date function to get the date and time in the American Central timezone. So when a user clicks the button, the button calls the getDateTime jQuery function we wrote which contains out ajax request, the ajax request, requests the our PHP file, gets the data from the PHP file and then displays the data in our date-div without reloading the whole page. I hope this tutorial helps someone just learning Ajax. Please feel free to leave any comments.

Here is the full code displayed:

index.php file

<!doctype html>
<html>
    <head>
		<meta charset="utf-8" />
		<title>Super Simple Ajax jQuery PHP Tutorial</title>
		<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
		<style type="text/css">

			body {
				background: #ecf0f1;
				color: #2c3e50;
			}
			h1 {
				color: #2c3e50;
			}
			#container {
				margin: 0 auto;
				width: 400px;
			}
			#date-div {
				width: 400px;
				height: 250px;
				border: 3px solid #2c3e50;
				margin: 0 auto;
				margin-top: 20px;
			}
			.pdate {
				color: #2c3e50;
				font-size: 16px;
				font-weight: bold;
				margin-left: 10px;
			}
			.btn-primary {
				background-color: #428bca;
				border-color: #357ebd;
				color: #fff;
				cursor: pointer;
				border-radius: 4px;
				display: inline-block;
				font-size: 16px;
				font-weight: 400;
				padding: 6px 12px;
				text-align: center;
				vertical-align: middle;
				white-space: nowrap;
			}
		</style>
		<script>
	
	function getDateTime() {
		var request = $.ajax({
			url: "ajax.php",
			type: "GET",			
			dataType: "html"
		});

		request.done(function(msg) {
			$("#date-div").html(msg);			
		});

	}
</script>
	</head>
	<body>
		<div id="container">
			<h1>Ajax jQuery PHP Tutorial</h1>
			What is the current time and date in Central Time Zone:<br />
				<div id="date-div">
					<!-- this is where the ajax file call wiil be displayed in web browser -->
				</div>
				<br/>
			<input type="button" class="btn-primary" value="Get Date & Time" onclick="getDateTime();" />
		</div>
	</body>
</html>

ajax.php file

<?php
date_default_timezone_set('America/Chicago');
echo '<p class="pdate">The Date is ' . date("m/d/y") .' .</p>';
echo '<br/>';
echo '<p class="pdate">The Time is ' . date('g:i:s A') . ' .</p>';

Zipped Demo Source Files

Blog, PHP, Web Development,

Leave a Comment

Your email address will not be published.