Computer Programming web Web programming Tips



AJAX with PHP Example

By Sergey Skudaev


AJAX stays for Asynchronous JavaScript and XML

Using AJAX is it possible to send data from web page to the webserver without submitting a webpage.

In this example a form has 3 arrays of fields: firstname, lastname and email. The form displays data from a database table. A user can change data on the form and click the Update button.

JavaScript code that sends data to the server using POST method:

<script>
$(document).on("submit","#frmMain",function(e){
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(data){
var res = document.getElementById("response");
res.innerHTML=data;
});
});
</script>

On the server side, data is received and processed by PHP code:

update_ajax.php

$lastnamear=array();
$firstnamear=array();
$emailar=array();
$vidar=array();
$count=0;

if(isset($_POST['firstname']))
$firstnamear=$_POST['firstname'];

if(isset($_POST['lastname']))
$lastnamear=$_POST['lastname'];

if(isset($_POST['email']))
$emailar=$_POST['email'];

if(isset($_POST['vid']))
$vidar=$_POST['vid'];

$count=sizeof($firstnamear);

for($i=0; $i<$count; $i++)
{
$sql="update visitors set
firstname= '".$firstnamear[$i]."',
lastname='".$lastnamear[$i]."',
email= '".$emailar[$i]."'
where vid=".$vidar[$i];

	if(!mysql_query($sql))
	{
	echo mysql_errno() . ": ";
	echo mysql_error() . "<br>";
	}
	else
	echo "Visitor's:".$firstnamear[$i]." ". $lastnamear[$i]." record updated!<br>";
}

The PHP page that receives and processes POST data has nothing special. It is a regular PHP page. To get feed back from the PHP page it has to echo output mesage.

This feed back message will be passed to the original page in the data variable in the following Javascript code line:

$.post($(this).attr("action"),$(this).serialize(), function(data){

On the original page this feed back message is displayed at the bottom of the table in a div with response ID:

var res=document.getElementById("response");
res.innerHTML=data;

AJAX DEMO
First NameLast NameEmail

Change a name or email and click the Update button


The form for entering data has input validation. For that a JavaScript valForm() function is used.

<script>
function valForm()
{
      var err = 0;
      //get form elements array
      var elem = document.getElementById('frmMain').elements;

   //walk through the array and check each element name and value.
   //if input text is empty display red borders.
  for(var i = 0; i < elem.length; i++)
  {
	if((elem[i].value=="")&& (elem[i].name =="firstname[]"))
	{
		elem[i].style.border="3px solid #ff0000";
		err++;
    }

	if((elem[i].value=="")&& (elem[i].name =="lastname[]"))
	{
		elem[i].style.border="3px solid #ff0000";
		err++;
    }
	if(((elem[i].name=="email[]")&& (elem[i].value ==""))
	{
		elem[i].style.border="3px solid #ff0000";
		err++;
    }
  } //for
  		if(err>0)
  		return false;
 }
</script>

This function walks through array of fields and if a text field is empty displays red borders around the text field.

To remove red borders when user places cursor inside an empty text field, function toDefault() is used:

function toDefault(x)
{
x.style.color="black";
x.style.border="1px solid #aaa";
}

There is an example, how to call this function:

<input type="text" name="firstname[]" value="'.$firstname.'" onfocus = "toDefault(this);"/>

My eBooks on Amazon.com

US    UK    BR    CA
US    UK    BR    CA
US   UK   BR   CA