How to Manage Sessions in PHP page with Ajax Request

Hi,
I am a newbie on PHP and trying out the ajax dynamically from PHP/HTML page.

The scenario I am having is:
I am saving customer data from php/html form directly into MySQL by calling the php file. The files code are:

<html>
	<head>
		<title>Adding Table Row Dynamically using Javascript</title>
		<script type="text/javascript" href="scripts/utls.js">
		</script>
		<script type="text/javascript">
			function createRequest()
{
	try{
		request=new XMLHttpRequest();
	   }
	catch(tryMS)
	{
		try
		{
			request=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(otherMS)
		{
			try
			{
				request=new ActiveXObject("Microsoft.XMLHTTP");	
			}
			catch (failed)
			{
				request=null;
			}
		}
	}
				
	return request;
}
			function addCustomer()
			{
				/*alert('Inside Add Customer Function();');*/
				
				
				if(request.readyState==4)
				{
					if(request.status==200)
					{
						
						if(request.responseText=="okay")
						{
							var table=document.getElementById("customertable");
							var rowCount = table.rows.length;
							var row = table.insertRow(rowCount);
							var cell1 = row.insertCell(0);
							var cell2 = row.insertCell(1);
							var cell3 = row.insertCell(2);
							var cell4 = row.insertCell(3);
							cell1.innerHTML=document.getElementById("cname").value;
							cell2.innerHTML=document.getElementById("add1").value;
							cell3.innerHTML=document.getElementById("add2").value;
							cell4.innerHTML=document.getElementById("city").value;
						}
						else
						{
							alert(request.responseText);
						}
					}
				}
}
			//Function that will create request
			
			function addToDB()
			{
				request=createRequest();
				if(request==null)
				{
					alert("Unable to post data to the database Please try again later");
					return;
				}
				else
				{
					var url="addCustomer.php";
					var requestData="cname=" +
					escape(document.getElementById("cname").value) + "&add1=" +
					escape(document.getElementById("add1").value) + "&add2="  +
					escape(document.getElementById("add2").value) + "&city="  +
					escape(document.getElementById("city").value);
					request.onreadystatechange=addCustomer;
					request.open("POST",url,true);
					request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
					request.send(requestData);

				}
			}
		</script>
	</head>
	<body>
		<h1>Customer Data</h1>
		<table name="customertable" id="customertable" border="1px">
			<tr>
				<th>Customer Name</th>
				<th>Address-1</th>
				<th>Address-1</th>
				<th>City</th>

			</tr>
		</table>
		<br/>
		<h1>Enter Customer Details</h1>
		<div style="border:1px solid #dedede; width:400px;padding:10px;">
		<form name="cform" action="addcustomer.php" method="post">
			<label for="cname" style="width:50px;">Customer Name:</label>
			<input type="text" name="cname" id="cname"/><br/>
			<label for="cname" style="width:50px;">Address 1:</label>
			<input type="text" name="add1" id="add1"/><br/>
			<label for="cname" style="width:50px;">Address 2:</label>
			<input type="text" name="add2" id="add2"/><br/>
			<label for="cname" style="width:50px;">City:</label>
			<input type="text" name="city" id="city"/><br/>
			<input type="button" value="Add Customer" onclick="addToDB();">
		</form>
		</div>
	</body>
</html>

The Backend PHP File is:

<?php
	$cname=$_REQUEST['cname'];
	$address1=$_REQUEST['add1'];
	$address2=$_REQUEST['add2'];
	$city=$_REQUEST['city'];
	if(isset($_POST['cname']) && isset($_POST['add1']) && isset($_POST['add2']) && isset($_POST['city']) )
	{
		$dbc=mysqli_connect('localhost','root','','city') or die('Error Connecting MySQL');
		$query="INSERT INTO customer (cname,add1,add2,city) VALUES('$cname','$address1','$address2','$city')";
		$result=mysqli_query($dbc,$query) or die('Error Inserting Row');
		if($result)
		{
			echo 'okay';
		}
		else
		{
			echo 'denied in result';
		}
	}
	else
	{
		echo 'denied in if';
	}
	mysqli_close($dbc);
?>

The Mysql Table is simple: cust_id(int, autoincrement), cname VARCHAR(40), add1 VARCHAR(40), add2 VARCHAR(40), city VARCHAR(30).

The things I want to know are:

  1. How can I change this html into php i.e. is it simple by adding <?php ?> around the code or leave the coding of html as it is and save the file with .php extention.

  2. How to manage the sessions in PHP i.e. when I make the AJAX call from javascript function i.e.

request.onreadystatechange=addCustomer;
request.open(“POST”,url,true);
request.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”);
request.send(requestData);

How the sessions data will be sent is it sent automatically behind the scenes by the browser or I need to send the data manually along with ajax call. I know I need to use session_start() at the start of .php file (The existing HTML File) but the thing is how does the sessions data will be sent and managed Do I need to do this manually or it will be done by browser.

Any help will be highly appreciated.

Thanks
PHPNewBie

Hi, in answer to your questions:

  1. Yes, you’d need to do both - <?php ?> tags around any php code, and change the file extension to .php
  2. You don’t need to do anything extra, as the browser will send the session ID to the server with each request, even over ajax.

Another thing, you should be escaping any data that you’re using in your DB queries (http://www.php.net/manual/en/mysqli.real-escape-string.php), or using prepared statements ([URL=“http://php.net/manual/en/mysqli.quickstart.prepared-statements.php”]http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) to avoid SQL injection attacks.