PHP Jquery and Ajax


PHP, Jquery and Ajax Tutorial

The purpose of this article is to explain several options for which to use PHP and Ajax. Ajax has been around a long a time and there are multiple reasons why a developer would want to use it.

However, what ranks it high on the list is its ability to make a call to another file and return data that can be presented on a page without the need for a refresh. The data from the requested file can be a string or data queried from a database.

But, retrieving data without refreshing is only one such advantage of Ajax. You may want to post data to the Ajax file and perform any CRUD operation like Insert, Update or Delete as well as return updated information. All this is possible with Ajax.


How is a typical Ajax Request Performed?

To start with, it often begins with a POST or GET request that sends variables to the Ajax file. Since POST is more secure and often the programmer's choice for dealing with data from forms, the following examples will explain how to make Ajax calls with POST variables.

Although the examples in this tutorial will show how to output data on the page without a refresh, please keep in mind there are two important ways to do this. One method, is to print a string in the Ajax file while the other is to print JSON data from the Ajax file. With the former, you can easily output any desired HTML as a string and it will magically appear exactly as you code it in the called Ajax file.

However, if you decide to print(echo) JSON data from the file, you have the option to parse it and manipulate it in Jquery which can allow for many more options in terms of placing various portions of data on the page. If that sounds confusing, the examples should make it much easier to see how it is done.

Now, let's let the examples take over. Each example consists of 2 files. One file is the page that is loaded in the browser and the Ajax file is the one that is called from the main file.

Example #1

Overview

When the button with the 'contacted' class is clicked, it triggers the Jquery. After the click function, the Javascript variable myurl is the value of 'yahoo.com'.

Immediately after the variable creation, the Ajax shown by '$.ajax' takes over. As you can see, it is a POST request that calls the my_ajax_print_php.php file.

This variable myurl is posted as my_variable, thus, when it arrives at the Ajax file it becomes $_POST['my_variable']. 

Once the variable arrives at the Ajax file, you can do whatever you want with it. If you look at the file in this example, you see a potential query you can use to output data. Meanwhile, I will explain what is happening in this case since we are only going to parse an array.

The array is parsed and printed. But, keep in mind that this takes place in the success function in the main file. The entire data that was printed in the Ajax file becomes the variable msg. As you can see, that output is sent to 2 locations on the page; the first is the div element with the id 'vanillajs' and the second is the div element with the id 'jqueryjs'.

Main File

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script type="text/javascript">

$(document).ready(function () {

$('.contacted').click(function () {

var myurl = $(this).siblings('#myurl').val();

$.ajax({

type: "POST",
cache: false,
url: "my_ajax_print_php.php",
data: {my_variable: myurl},

success: function (msg) {
alert("Success!");
document.getElementById("vanillajs").innerHTML = msg;
$("div#jqueryjs").html("<p>" + msg + "</p>");

}

});

});

});

</script>
</head>
<body>
HTML

<form method="POST" action="">
<input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
<input id="contacted" class="contacted" type="button" name="contacted" value="Submit"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

Ajax File

$numbers = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);

foreach ($numbers as $key => $number) {
echo "<br/>" . $key . " - " . $number;
}

/* Query Sample
$user_id = mysqli_real_escape_string($db,$_POST['my_variable']);
$command = "SELECT * FROM user WHERE id = '" . $user_id . "'";
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . "<br/>";
}
*/

Example #2

This next example will be very similar to the first example, except the data will be returned as JSON and manipulated with Jquery. If you look closely, the main difference is the addition of the DataType:JSON is the Ajax request and the printed data from the Ajax file uses the json_encode() function.

Asides from those two details explained above, you will see the output is more complicated. With the Ajax file, there are 2 numbers arrays that are created. Thus, each of those transforms into msg[0] and msg[1]. Within each array, there are items which take on indexed values. Thus, The number 2 from the first array is actually msg[0][1]. Always remember keys start at 0 and not 1, thus msg[0][1] is the first array with the second item.

If you look at the HTML and compare with the Jquery inside the success function, you will see why those numbers are what they are.

Main File

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script type="text/javascript">


$(document).ready(function () {

$('.contacted').click(function () {

var myurl = $(this).siblings('#myurl').val();

$.ajax({

type: "POST",
cache: false,
url: "my_ajax_indexed.php",
data: {my_variable: myurl},

success: function (msg) {
alert("Success!");
document.getElementById("vanillajs").innerHTML = msg[0][3];
$("div#jqueryjs").html("<p>" + msg[1][2] + "</p>");
//$( "div#jqueryjs" ).html("<p>Add here</p>");

jQuery.each(msg, function (key, val) {
alert(key + "=" + val);
jQuery.each(val, function (key2, val2) {
alert(key2 + "=" + val2);
});
});
},
dataType: "json"

});

});

});

</script>
</head>
<body>
HTML

<form method="POST" action="">
<input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
<input id="contacted" class="contacted" type="button" name="contacted" value="Submit"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

Ajax File

$numbers[] = array(1, 2, 3, 4, 5);
$numbers[] = array(6, 7, 8);
echo json_encode($numbers);

Example#3

This final example shows an associative array that is printed in the Ajax file and manipulated in the Jquery from the main file. This example is very similar to the last example since it returns a JSON string. The difference is that the arrays are associative; thus have named keys instead of numerical keys like the ones in the previous example. Like the previous example, there are two arrays that become msg[0] and msg[1]. Therefore, to access any item from the first array can be done by using msg[0] followed by the item key. Thus, the item from the second array with a key of 6 can be accessed in Jquery as msg[1].six. 

Main File 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script type="text/javascript">


$(document).ready(function () {

$('.contacted').click(function () {

var myurl = $(this).siblings('#myurl').val();

$.ajax({

type: "POST",
cache: false,
url: "my_ajax_multi.php",
data: {my_variable: myurl},

success: function (msg) {
alert("Success!");
document.getElementById("vanillajs").innerHTML = msg[0].three;
$("div#jqueryjs").html("<p>" + msg[1].eight + "</p>");
//$( "div#jqueryjs" ).html("<p>Add here</p>");

jQuery.each(msg, function (key, val) {
alert(key + "=" + val);
jQuery.each(val, function (key2, val2) {
alert(key2 + "=" + val2);
});
});
},
dataType: "json"

});

});

});

</script>
</head>
<body>
HTML

<form method="POST" action="">
<input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
<input id="contacted" class="contacted" type="button" name="contacted" value="Submit"/>
</form>

<div id="vanillajs"><b>Person info will be listed here.</b></div>

<div id="jqueryjs"><b>Person info will be listed here.</b></div>

</body>
</html>

Ajax File

$numbers[] = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
$numbers[] = array('six' => 6, 'seven' => 8, 'eight' => 8);
echo json_encode($numbers);

Ajax Security

The previous examples have shown how to use Ajax with simple, limited coding. But, in the real world, security should never be left out during the building process. With Ajax, sessions persist which means you can make files only accessible to authenticated uses. On top of that, you could also track what authenticated users are making Ajax requests, bit, you may find that unnecessary.

In addition, to securing your Ajax requests by using authenticated sessions, you can add a session and a hidden input to eliminate Cross Site Request Forgery since the token in the hidden input must match the session on the server, something a malicious user cannot spoof. In addition to that, you can filter any output with htmlentities() function in order to make sure that potential scripts in database fields cannot be executed.