Computer Programming web Web programming Tips



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