Login

Php ajax

Rodrigo

By Rodrigo

Created 2014-06-26 06:45:25 Modified 2014-06-26 06:45:25

Asynchronous JavaScript and XML (AJAX) is a very useful technique, to send and/or retrieve data via "post" or "get" without reload the full page again, the main idea is to retrieve or send data to the database, it make no sense if we use ajax without retrieving or sending data to the database, in that case javascript/jquery would be the best choice.

In this tutorial we are going to develop a very basic php form with 3 selects and we are going to see the difference between a normal request and an ajax request, filtering with normal request and ajax request

this tutorial was written using the following gear:

  • Hardware:           laptop Thinkpad E430 Intel I5, 4gb Ram, 500gb HDD
  • OS:                    x86_64 GNU/Linux Ubuntu 14.10
  • Kernel:               3.13.0-29-generic
  • IDE/Text editor:   Gedit 3.10.4
  • PHP:                   PHP 5.4.16 (cli) (built: Jun 24 2013 12:08:02) 
  • DB:                     Mysql 5.5.31
  • Mysql client:        PhpMyadmin 4.0.4.1
  • Browser:             Chromium Version 34.0.1847.116 Ubuntu 14.04 aura (260972)

 

1.- Creating the db:

First we need a database to retrieve the data shown on the comboboxes, let's take the following script and run it on mysql

CREATE database ajaxExample;
USE ajaxExample;

CREATE TABLE categories(
	id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
	name VARCHAR(45) NOT NULL
);

CREATE TABLE sub_categories(
	id INT NOT NULL PRIMARY KEY AUTO_INCREMENT ,
	category_id INT NOT NULL ,
	FOREIGN KEY ( category_id ) REFERENCES categories( id ) ON DELETE CASCADE ON UPDATE CASCADE ,
	name VARCHAR( 45 ) NOT NULL
);

INSERT INTO categories(name)VALUES('Programming');
INSERT INTO categories(name)VALUES('Database');
INSERT INTO categories(name)VALUES('UML');

INSERT INTO sub_categories(category_id,name)VALUES(1,'Java');
INSERT INTO sub_categories(category_id,name)VALUES(1,'Csharp');
INSERT INTO sub_categories(category_id,name)VALUES(1,'php');

INSERT INTO sub_categories(category_id,name)VALUES(2,'MSQL');
INSERT INTO sub_categories(category_id,name)VALUES(2,'PLSQL');
INSERT INTO sub_categories(category_id,name)VALUES(2,'MYSQL');

INSERT INTO sub_categories(category_id,name)VALUES(3,'Use Case Diagram');
INSERT INTO sub_categories(category_id,name)VALUES(3,'Sequence diagram');
INSERT INTO sub_categories(category_id,name)VALUES(3,'Class diagram');

2.- Creating the index page:

alright once created the database we can create our index.php which uses the previous data

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ejemplo de ajax</title>
<link href="http://www.joni2back.com/favicon.ico" rel="shortcut icon" />
<script type="text/javascript" src="jquery-2.0.3.js"></script>
<script type="text/javascript" src="jquery-migrate.js"></script>
<script>
$(document).ready(function(){
    var url;
    url='ajax.php';//this url
    
    
    $('#category_select').change(function() {
        buscaDatosAjax($('#category_select').val(),url);
        
    });	
    
    
    function buscaDatosAjax(object,url){    
    	
                var parametros = {
                        "category" : object
                };
                $.ajax({
                        data:  parametros,
                        url:    url,
                        type:  'post',
                        beforeSend: function () {
                            $("#sub_category_select").html("<option value='...'>...</option>");
                        },
                        success:  function (response) {
                            $("#sub_category_select").html(response);
							$("#h1req").html("Ajax request");
                        }
                });
        }    
});//fin jquery
</script>
</head>
<body>


<form method="post">
<?php 
	if (!empty($_POST))
		echo "<h1 id='h1req'>Normal request</h1>";
	else
		echo"<h1>Ajax example<h1>";
?>

	<table>
	<tr>
		<th>category Ajax</th> <th>category normal</th> <th>sub category</th>
	</tr>
	<tr>
		<td>
			<select id="category_select" name="category">
			<option value=0>All</option>
				<?php 
					mysql_connect("127.0.0.1","root","root");
					mysql_select_db("ajaxExample");					
					$data = "SELECT id, name FROM categories";
					$result = mysql_query($data);
					while($data = mysql_fetch_array($result))
					if (!empty($_POST) && $_POST['category']==$data['id'])	
						echo("<option value=".$data['id']." selected='selected'>".$data['name']."</option>");
					else
						echo("<option value=".$data['id'].">".$data['name']."</option>");

				?>				
			</select>
		</td>
		<td>
			<select id="category_select_normal" name="category">
			<option value=0>All</option>
				<?php 
					mysql_connect("127.0.0.1","root","root");
					mysql_select_db("ajaxExample");					
					$data = "SELECT id, name FROM categories";
					$result = mysql_query($data);
					while($data = mysql_fetch_array($result))
					if (!empty($_POST) && $_POST['category']==$data['id'])	
						echo("<option value=".$data['id']." selected='selected'>".$data['name']."</option>");
					else
						echo("<option value=".$data['id'].">".$data['name']."</option>");

				?>				
			</select>
		</td>
		<td>
			<select id="sub_category_select" name="sub_category">
				<?php					
					mysql_connect("127.0.0.1","root","root");
					mysql_select_db("ajaxExample");
					
					if (!empty($_POST) && $_POST['category']!=0)//cuando sea post y distinto de 0; when it's post and non 0;
						$data = "SELECT sub_categories.id, sub_categories.name FROM sub_categories INNER JOIN categories ON sub_categories.category_id = categories.id WHERE categories.id=".$_POST['category'];
					else//sin filtro; without filter
						$data = "SELECT id, name FROM sub_categories";

					$result = mysql_query($data);
					while($data = mysql_fetch_array($result)){
					  echo("<option value=".$data['id'].">".$data['name']."</option>");
					}

				?>				
			</select>
		</td>
	</tr>
	</table>
	<input type="submit" value="submit"/>
</form>
</body>
</html>

3.- Creating the AJAX page:

ok, so now we are going to create a php page which return (echo) plain html, so we are going to take this retrieved html and injecting in the main page, in this case we are going to retrieve data for filtering the next combobox, 1:n; 2 comboboxes, a typical web problem when you do not know how to refresh the "n" combobox without reload the whole page, let's create the "AJAX" page

<?php					
	mysql_connect("127.0.0.1","root","root");
	mysql_select_db("ajaxExample");
	
	if (!empty($_POST) && $_POST['category']!=0)//cuando sea post y distinto de 0; when it's post and non 0;
		$data = "SELECT sub_categories.id, sub_categories.name FROM sub_categories INNER JOIN categories ON sub_categories.category_id = categories.id WHERE categories.id=".$_POST['category'];
	else//sin filtro; without filter
		$data = "SELECT id, name FROM sub_categories";

	$result = mysql_query($data);
	while($data = mysql_fetch_array($result)){
	  echo("<option value=".$data['id'].">".$data['name']."</option>");
	}

?>

4.- Watching the requests:

Up to this point everything is done, so let's take a look at the AJAX request; we will not worry about normal request, this is an AJAX tutorial, ok let's enable the "AJAX" log press f12 on google-chrome (chromium) and click the small gear

then find the "log XmlhttpRequests" checkbox and enable it

now go to "console", and change the "category" ajax combobox

you will see now the details of the AJAX request on the console log

if you click it you are going to see the network details

then click the network detail "ajax.php" and you will see the full detail for instance let's click "Response" and that's very useful when you have an error, or the retrieving data is not correct.

 

Download it in https://docs.google.com/file/d/0BwOqSob-RrBOYW9HQ3VwRFUzWU0/edit?pli=1

5.- Conclusion:

AJAX is not language, is an skill to handle web data, ajax can be used with any  server language (Java, Ruby, Python, C#, etc...) even without a server language which is pretty useless, javascript/jquery will be the answer then

6.- Reference links:




comments powered by Disqus