How to delete table row using ajax call back method

Hi,
I am working on a ajax add/remove record method using html/ajax/javascript (front end) and scenario works like this:

  1. Form is displayed and table is displayed

  2. When user enters data into the form through the ajax call the table the record is added to the database and new row is added into the front end of page without page refresh.

  3. When deleting the row user selects the checkbox from the table showing in the front end and then click delete. The ajax function is invoked to delete the selected row from the table but I need to remove the row also from the front end and issue is like this:

First database ajax call is made to remove the row and my .php program returns success or failure string then in ajax callback method i.e.

request.onreadystatechange=removeCustomer;

in remove customer callback method I want to remove the corresponding row from the table. How can I get the selected table row in the call back method(In other words how does my ajax callback method request.onreadystatechange=removeCustomer; know which table to remove from the front end dynamically.

The partial code is:

function removefromDB()
{
	alert('Inside Delete Cust');
	request=createRequest();
				if(request==null)
				{
					alert("Unable to Delete data from the database Please try again later");
					return;
				}
				else
				{
					try {
							var table = document.getElementById("customertable");
				             var rowCount = table.rows.length;

							for(var i=0; i<rowCount; i++)
							{
								 var row = table.rows[i];
								 var chkbox = row.cells[0].childNodes[0];
									if(null != chkbox && true == chkbox.checked)
									{
					                    var cname=row.cells[1].innerText;
										var add1=row.cells[2].innerText;
										var add2=row.cells[3].innerText;
										var city=row.cells[4].innerText;
										var url="removeCustomer.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=removeCustomer;
										request.open("POST",url,true);
										request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
										request.send(requestData);
										table.deleteRow(i);
										rowCount--;
										i--;
									}
							}
					}
					catch(e)
					{
		                alert(e);
				    }
					

				}
}

Any suggestions would be highly appreciated on this part.

Thanks
PHPnewbie

Hi there,

When a user selects a row, then presses delete, what does the code for the resulting ajax request look like?
Could you post that here?

You have to be passing the row id to the PHP script, so that the PHP script knows what to delete. I would have thought you could use that in the success callback.

Hi,
The resulting code I have not yet developed because I am confused on how to manage the request callback function. I am passing this to ajax request:
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=removeCustomer;
request.open(“POST”,url,true);
request.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”);
request.send(requestData);

But right now only getting success or fail in the .php file should I change the coding style or something like that.

Thanks
PHPNewBie

Ok, well your basic AJAX POST request will look like this:

var ajaxRequest;

try{
  // Opera 8.0+, Firefox, Safari
  ajaxRequest = new XMLHttpRequest();
} catch (e){
  // Internet Explorer Browsers
  try{
    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try{
      ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e){
      // Something went wrong
      alert("Your browser broke!");
      return false;
    }
  }
}

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){
    if (ajaxRequest.status==200 || window.location.href.indexOf("http")==-1){
      // Do stuff here
    }
    else{
     alert("An error has occured making the request")
    }    
  }
}

var id = document.getElementById(checkBoxID).value;
var params = "id=" + id;
ajaxRequest.open("POST", "myScript.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(params);

You are essentially getting the value of the check box whose row you want to delete and passing it to your PHP script asynchronously.
The PHP script will then process this value and return a response depending on whether the delete was successful or not (this will be available in the variable ajaxRequest.responseText).

Where I have written // Do stuff here, you should then query this response and if the delete was a success, you can remove the deleted row from your page.
e.g.

document.getElementById("myTable").deleteRow(id);

FWIW, I find the added layer of abstraction that jQuery adds to working with AJAX, well worth the hit of including the jQuery library.

I hope this helps you.

<html>
	<head>
		<title>Adding Table Row Dynamically using Javascript and Ajax</title>
		<script type="text/javascript" href="scripts/utils.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 to remove data from DB
function removefromDB()
{
	alert('Inside Delete Cust');
	request=createRequest();
				if(request==null)
				{
					alert("Unable to Delete data from the database Please try again later");
					return;
				}
				else
				{
					try {
							var table = document.getElementById("customertable");
				             var rowCount = table.rows.length;

							for(var i=0; i<rowCount; i++)
							{
								 var row = table.rows[i];
								 var chkbox = row.cells[0].childNodes[0];
									if(null != chkbox && true == chkbox.checked)
									{
					                    var cname=row.cells[1].innerText;
										var add1=row.cells[2].innerText;
										var add2=row.cells[3].innerText;
										var city=row.cells[4].innerText;
										var url="removeCustomer.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=removeCustomer;
										request.open("POST",url,true);
										request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
										request.send(requestData);
										table.deleteRow(i);
										rowCount--;
										i--;
									}
							}
					}
					catch(e)
					{
		                alert(e);
				    }
					

				}
}
//Add row to the table after adding row to the database
			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);
							var cell5 = row.insertCell(4);
							var cell6 = row.insertCell(5);
							var element1 = document.createElement("input");
				            element1.type = "checkbox";
							element1.name="chkbox[]";
							cell1.appendChild(element1);

							
							cell2.innerHTML=document.getElementById("cname").value;
							cell3.innerHTML=document.getElementById("add1").value;
							cell4.innerHTML=document.getElementById("add2").value;
							cell5.innerHTML=document.getElementById("city").value;
							var btn=document.createElement("button");
							var t=document.createTextNode("Delete");
							btn.appendChild(t);
							btn.addEventListener("click",removefromDB);
							cell6.appendChild(btn);
						}
						else
						{
							alert(request.responseText);
						}
					}
				}
}
			//Function that will create request and add data to database
			
			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>Select</th>
				<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>

I am not using JQuery and using Plain Ajax… Please any suggestions on how to delete the table from front end. I successfully delete the row from the database its just the table row I need to delete

I just need to know how can I remove the table row from the ajax callback function and how do my ajax callback function know how to know which table row to delete.

In this line:

if(null != chkbox && true == chkbox.checked){

you determine that the row is marked for deletion.

You could at this point save a reference to this row and delete it upon a successful completion of the AJAX request.

To be honest though, it is a little messy.
If I were you I would prefer to work with an id.