article

Saturday, August 17, 2013

Ajax Add & Delete MySQL records using jQuery & PHP

Ajax Add & Delete MySQL records using jQuery & PHP 

Create Table

CREATE TABLE IF NOT EXISTS `add_delete_record` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
//index.php
<html>
<head>
<title>Ajax Add/Delete Record with jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("#FormSubmit").click(function (e) {
			e.preventDefault();
			if($("#contentText").val()==='')
			{
				alert("Please enter some text!");
				return false;
			}
		 	var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
			jQuery.ajax({
			type: "POST", // Post / Get method
			url: "response.php", //Where form data is sent on submission
			dataType:"text", // Data type, HTML, json etc.
			data:myData, //Form variables
			success:function(response){
				$("#responds").append(response);
				$("#contentText").val(''); 
			},
			error:function (xhr, ajaxOptions, thrownError){
				alert(thrownError);
			}
			});
	});

	$("body").on("click", "#responds .del_button", function(e) {
		 e.returnValue = false;
		 var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
		 var DbNumberID = clickedID[1]; //and get number from array
		 var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
		 
			jQuery.ajax({
			type: "POST", // Post method
			url: "response.php", 
			dataType:"text", // Data type, HTML, json etc.
			data:myData, //Form variables
			success:function(response){
				$('#item_'+DbNumberID).fadeOut("slow");
			},
			error:function (xhr, ajaxOptions, thrownError){
				//On error, we alert user
				alert(thrownError);
			}
			});
	});
});
</script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content_wrapper">
<ul id="responds">
<?php
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
  echo '<li id="item_'.$row["id"].'">';
  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
  echo '<img src="images/icon_del.gif" border="0" />';
  echo '</a></div>';
  echo $row["content"].'</li>';
}
mysql_close($connecDB);
?>
</ul>
    <div class="form_style">
    <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
    <button id="FormSubmit">Add record</button>
    </div>
</div>
</body>
</html>
//config.php
<?php
$username = "root"; 
$password = ""; 
$hostname = "localhost";
$databasename = 'test';
$connecDB = mysql_connect($hostname, $username, $password)or die('could not connect to database');
mysql_select_db($databasename,$connecDB);
?>
response.php
<?php
include_once("config.php");
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) 
{	
	/* 
	sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
	Strip tags, encode special characters.
	*/
	$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
	if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
	{
		  $my_id = mysql_insert_id(); 
		  echo '<li id="item_'.$my_id.'">';
		  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
		  echo '<img src="images/icon_del.gif" border="0" />';
		  echo '</a></div>';
		  echo $contentToSave.'</li>';
	}else{
		header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
		exit();
	}
}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{	
	$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 
	if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
	{    
		header('HTTP/1.1 500 Could not delete record!');
		exit();
	}
}
else
{
	//Output error
	header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
mysql_close($connecDB);
?>

Related Post