Skip to main content

To-do List Application with Ajax, PHP & MySQL

In our previous tutorial, we have explained how to implement Save TinyMCE Editor Content with PHP & MySQL. In this tutorial you will learn how to implement To-do List Application with Ajax, PHP & MySQL.

To-do List Applications are created to allow users to manage their daily do-list. The user can add their do items, close the list items when completed and also remove these permanently from completed list.

So if you’re looking for developing you own To-do list application, then you’re here at right place. in this tutorial you will learn how to develop Do-list application with Ajax, PHP and MySQL.

We will cover this tutorial in easy steps to create live demo with functionality to add To-do items and list them. Allow users to move Do-to items into completed list when these completed. Also allow users to remove completed items from it’s list.

Also, read:

So let’s implement To-do application with Ajax, PHP and MySQL. The major files are:

  • index.php: PHP file to load TinyMCE editor to save content.
  • todo.js: A JavaScript file to handle ajax and items add remove functionality.
  • action.php: Action file to load data according request method.
  • Task.php: A class to hold methods related To-do items insert, update.

Step1: Create MySQL Database Table

First we will create MySQL database table todo to store To-do items to manage.

CREATE TABLE `todo` (
  `id` int(11) NOT NULL,
  `task` mediumtext NOT NULL,
  `status` enum('0','1','2') DEFAULT '0',
  `created` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Add To-do Items to MySQL Database Table

We will create HTML form with an input and submit button to add Do-list items.

<form id="todoForm" name="todoForm" method="post">
	<input type="text" id="todo" name="todo" class="form-control add-todo" placeholder="Add todo">
	<input type="hidden" name="action" id="action" value="add" /><br>
	<button type="submit" id="add" name="add" class="btn btn-success saveButton">Add</button>
</form>

We will handle form submit with jQuery and make ajax request with action add to action.php to add new items and display on same page.

$(document).on('submit','#todoForm', function(event){
	var formData = $(this).serialize();
	$.ajax({
			url: "action.php",
			method: "POST",              
			data: formData,
			dataType:"json",
			success: function(data) {     
				var html = $("#taskHTML").html();					
				html = html.replace(/TO_DO_ID/g, data.id);
				html = html.replace(/TASK_NAME/g, data.task);					
				$("#sortable").append(html).fadeIn('slow');
				$('#todo').val('');
				countTodos();
			}
	});		
	return false;
});

We will check for action add in action.php and call method insert() from class Task.php to insert item to MySQL database table.

include_once 'class/Task.php';
$task = new Task($db);
if(!empty($_POST['todo']) && $_POST['todo'] && $_POST['action'] == 'add') {	
	$task->task = $_POST['todo'];	
	$task->insert();	
}

We will implement method insert() in class Task.php to insert records.

public function insert(){
		
	if($this->task) {

		$stmt = $this->conn->prepare("
			INSERT INTO ".$this->todoTable."(`task`)
			VALUES(?)");
					
		$stmt->bind_param("s", $this->task);
		
		if($stmt->execute()){	
			$lastTodo = $stmt->insert_id;
			$sqlQuery = "
				SELECT id, task, status, DATE_FORMAT(created,'%d %M %Y %H:%i:%s') AS todo_date
				FROM ".$this->todoTable." WHERE id = '$lastTodo'";
			$stmt2 = $this->conn->prepare($sqlQuery);				
			$stmt2->execute();
			$result = $stmt2->get_result();
			$record = $result->fetch_assoc();
			echo json_encode($record);
		}		
	}
}	

Step3: List To-do Items

We will call method getTodo() from class Task.php to get the list of To-do items. We will loop through items and list them.

<ul id="sortable" class="list-unstyled">				
<?php
$result = $task->getTodo(0);
while ($todo = $result->fetch_assoc()) {			
?>
	<li class="ui-state-default">
	<div class="checkbox">
	<label>
	<input type="checkbox" value="<?php echo $todo['id']; ?>" /><?php echo $todo['task']; ?></label>
	</div>
	</li>
<?php } ?>				
</ul>

We will implement method getTodo() in class Task.php to get To-do items list.

public function getTodo($type){		
	$sqlQuery = "
		SELECT *
		FROM ".$this->todoTable." 
		WHERE status = '$type' ORDER BY id DESC";
	
	$stmt = $this->conn->prepare($sqlQuery);
	$stmt->execute();
	$result = $stmt->get_result();			
	return $result;	
}

Step4: Complete To-do Items

We will handle functionality to mark To-do item as completed by checking checkbox.

$('.todolist').on('change','#sortable li input[type="checkbox"]',function(){
	if($(this).prop('checked')){
		var doneItem = $(this).parent().parent().find('label').text();
		$(this).parent().parent().parent().addClass('remove');
		var tasks = [];
		tasks.push($(this).val()); 			
		done(doneItem, $(this).val());
		countTodos();
		var todos = tasks.join(); 
		updateTask(todos, );
	}
});

We will update the To-do items status by calling function updateTask() to update items status to the database table with action updateTask.

function updateTask(itemIds) {	
	var action = 'updateTask';	
	$.ajax({
		url: "action.php",
		method: "POST",    
		data:{id: itemIds,  val:1, action:action},
		success: function(data) {     
			console.log("updated");
		}
	});		
}

We will check for action updateTask and call method update() in class Task.php.

if(!empty($_POST['action']) && $_POST['action'] == 'updateTask') {	
	$task->id = $_POST['id'];
	$task->val = $_POST['val'];	
	$task->update();	
}

We will implement the method update() in class Task.php to change the status of To-do items.

public function update(){
		
	if($this->id) {			
		$stmt = $this->conn->prepare("
			UPDATE ".$this->todoTable." 
			SET status = '".$this->val."'
			WHERE id IN (".$this->id.")");		
		
		if($stmt->execute()){
			return true;
		}
		
	}	
}

Step5: Renove To-do Items

We will handle functionality to remove completed items from completed items list and update items status.

$('.todolist').on('click','.remove-item',function(){
	removeItem(this);
	var id = $(this).attr('data-id');
	var action = 'updateTask';	
	$.ajax({
		url: "action.php",
		method: "POST",    
		data:{id: id, val:2, action:action},
		success: function(data) {     
			console.log("updated");
		}
	});		
});

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download

2 thoughts on “To-do List Application with Ajax, PHP & MySQL

  1. Hi,
    Not working on my server. What PHP version is correct?
    Database MariaDB is correct?

Comments are closed.