Monday, 23 May 2022

PHP CRUD Operations with JSON File using Ajax, jQuery Bootstrap 5

PHP CRUD Operations with JSON File using Ajax, jQuery Bootstrap 5

In this tutorial, we will show you how to make PHP CRUD Application with JSON file by using Ajax, jQuery and Bootstrap 5 library. With this tutorial, we will learn you how can we connect PHP script with JSON file and do CRUD (Create, Read, Update, Delete) operation with JSON file data and here we will Ajax and jQuery with Bootstrap 5 library and create single page JSON file CRUD application with PHP script. So under this tutorial, you can learn something new from this PHP JSON CRUD tutorial. So with the help of this tutorial you can build any simple web application in which you do not want to use any database and JSON file is the best option for store data and CRUD operation is mainly used for manage you web data. So here you can learn How to Read, Insert, Update and Delete data from JSON file using PHP Script with Ajax jQuery.

Under this tutorial, we have use following web technology has been use, so you can get clear understanding regarding this tutorial.

  • PHP
  • Ajax
  • jQuery
  • jQuery DataTable
  • Bootstrap 5

Following things we will cover under this tutorial.

  1. Read JSON File & Load Data in jQuery DataTables
  2. Add or Insert Data into JSON file using Bootstrap Modal
  3. Edit or Update Existing JSON File Data using Bootstrap Modal
  4. Delete or Remove JSON File Data

Step 1 - Read JSON File & Load Data in jQuery DataTables



This is first step of How can make PHP JSON file CRUD Application. So in this step, we will show you How to load JSON file data in jQuery DataTable. So here we have use jQuery DataTable for display JSON file data on Web Page in tabular format. So we can easily manage JSON file data and with the help of jQuery DataTable we can use Live Data searching feature, pagination, table column sorting feature without writing any line of code.

So for load data in jQuery Datatable first we have to create index.php and data.json file. So we will store data under this data.json file.

In index.php file, first we have to create one HTML table with id sample_data, so we will use id attribute value for initialize jQuery Datatable and convert simple HTML table to robust Datatable with searching, pagination, sorting feature.

In this step we have use JavaScript Data Source option for load data from JSON file in jQuery DataTable. In this tutorial, we have use getJSON() method for read data from JSON file and then after by using JavaScript code we have sort JSON file data according to datetime, so inserted data will be display first. Below you can find source code for load JSON file data in jQuery DataTable.





index.php

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <link href="https://cdn.datatables.net/1.12.0/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/dataTables.bootstrap5.min.js"></script>

        <title>PHP CRUD Operations with JSON File</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-4 mb-4 text-center text-danger">JSON CRUD operations in PHP | Load Data in jQuery DataTables</h1>
            <span id="message"></span>
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-sm-9">Sample Data</div>
                        <div class="col col-sm-3">
                            
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered" id="sample_data">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Gender</th>
                                    <th>Age</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>



<script>

$(document).ready(function(){

    load_data();

    function load_data()
    {
        var seconds = new Date() / 1000;

        $.getJSON("data.json?"+seconds+"", function(data){

            data.sort(function(a,b){

                return b.id - a.id;

            });

            var data_arr = [];

            for(var count = 0; count < data.length; count++)
            {
                var sub_array = {
                    'first_name' : data[count].first_name,
                    'last_name' : data[count].last_name,
                    'gender' : data[count].gender,
                    'age' : data[count].age,
                    'action' : ''
                };

                data_arr.push(sub_array);
            }

            $('#sample_data').DataTable({
                data : data_arr,
                order : [],
                columns : [
                    { data : "first_name" },
                    { data : "last_name" },
                    { data : "gender" },
                    { data : "age" },
                    { data : "action" }
                ]
            });

        });
    }

});

</script>


Step 2 - Insert or Add Data using Bootstrap Modal



After loading JSON file data in jQuery DataTable, now we we want to add new data in JSON file by using PHP script.

So here we have use Bootstrap 5 modal for add new data and this data will be submitted by using ajax to PHP and PHP script will validate form data and add data into JSON file.

index.php

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <link href="https://cdn.datatables.net/1.12.0/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/dataTables.bootstrap5.min.js"></script>

        <title>PHP CRUD Operations with JSON File</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-4 mb-4 text-center text-warning">JSON CRUD operations in PHP | Insert or Add Data using Bootstrap Modal</h1>

            <span id="message"></span>
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-sm-9">Sample Data</div>
                        <div class="col col-sm-3">
                            <button type="button" id="add_data" class="btn btn-success btn-sm float-end">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered" id="sample_data">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Gender</th>
                                    <th>Age</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

<div class="modal" tabindex="-1" id="action_modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="sample_form">
                <div class="modal-header">
                    <h5 class="modal-title" id="dynamic_modal_title"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">First Name</label>
                        <input type="text" name="first_name" id="first_name" class="form-control" />
                        <span id="first_name_error" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Last Name</label>
                        <input type="text" name="last_name" id="last_name" class="form-control" />
                        <span id="last_name_error" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <select name="gender" id="gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Age</label>
                        <input type="number" name="age" id="age" class="form-control" />
                        <span id="age_error" class="text-danger"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="id" id="id" />
                    <input type="hidden" name="action" id="action" value="Add" />
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary" id="action_button">Add</button>
                </div>
            </form>
        </div>
    </div>
</div>



<script>

$(document).ready(function(){

    load_data();

    function load_data()
    {
        var seconds = new Date() / 1000;

        $.getJSON("data.json?"+seconds+"", function(data){

            data.sort(function(a,b){

                return b.id - a.id;

            });

            var data_arr = [];

            for(var count = 0; count < data.length; count++)
            {
                var sub_array = {
                    'first_name' : data[count].first_name,
                    'last_name' : data[count].last_name,
                    'gender' : data[count].gender,
                    'age' : data[count].age,
                    'action' : ''
                };

                data_arr.push(sub_array);
            }

            $('#sample_data').DataTable({
                data : data_arr,
                order : [],
                columns : [
                    { data : "first_name" },
                    { data : "last_name" },
                    { data : "gender" },
                    { data : "age" },
                    { data : "action" }
                ]
            });

        });
    }

    $('#add_data').click(function(){

        $('#dynamic_modal_title').text('Add Data');

        $('#sample_form')[0].reset();

        $('#action').val('Add');

        $('#action_button').text('Add');

        $('.text-danger').text('');

        $('#action_modal').modal('show');

    });

    $('#sample_form').on('submit', function(event){

        event.preventDefault();

        $.ajax({
            url:"action.php",
            method:"POST",
            data:$('#sample_form').serialize(),
            dataType:"JSON",
            beforeSend:function()
            {
                $('#action_button').attr('disabled', 'disabled');
            },
            success:function(data)
            {
                $('#action_button').attr('disabled', false);
                if(data.error)
                {
                    if(data.error.first_name_error)
                    {
                        $('#first_name_error').text(data.error.first_name_error);
                    }
                    if(data.error.last_name_error)
                    {
                        $('#last_name_error').text(data.error.last_name_error);
                    }
                    if(data.error.age_error)
                    {
                        $('#age_error').text(data.error.age_error);
                    }
                }
                else
                {
                    $('#message').html('<div class="alert alert-success">'+data.success+'</div>');

                    $('#action_modal').modal('hide');

                    $('#sample_data').DataTable().destroy();

                    load_data();

                    setTimeout(function(){
                        $('#message').html('');
                    }, 5000);
                }
            }
        });

    });

});

</script>


action.php

<?php

//action.php

if(isset($_POST["action"]))
{
	$file = 'data.json';

	if($_POST['action'] == 'Add')
	{
		$error = array();

		$data = array();

		$data['id'] = time();

		if(empty($_POST['first_name']))
		{
			$error['first_name_error'] = 'First Name is Required';
		}
		else
		{
			$data['first_name'] = trim($_POST['first_name']);
		}

		if(empty($_POST['last_name']))
		{
			$error['last_name_error'] = 'Last Name is Required';
		}
		else
		{
			$data['last_name'] = trim($_POST['last_name']);
		}

		$data['gender'] = trim($_POST['gender']);

		if(empty($_POST['age']))
		{
			$error['age_error'] = 'Age is required';
		}
		else
		{
			$data['age'] = trim($_POST['age']);
		}

		if(count($error) > 0)
		{
			$output = array(
				'error'		=>	$error
			);
		}
		else
		{
			$file_data = json_decode(file_get_contents($file), true);

			$file_data[] = $data;

			file_put_contents($file, json_encode($file_data));

			$output = array(
				'success' => 'Data Added'
			);
		}

		echo json_encode($output);
	}
}

?>


Step 3 - Update or Edit Data using Bootstrap Modal



Under this CRUD Operation with JSON File in PHP Tutorial, for Update or Edit JSON file data, here also we have use Bootstrap Modal with Ajax, jQuery and PHP Script.

For Edit or Update JSON file data, first we will create Edit button in each row of jQuery DataTable, this is because we have load JSON file data in jQuery DataTable.

After this, we will write jQuery Script for fetch single array of JSON file data, by click on edit button, and it will send Ajax request to PHP Script for fetch single array index of data from JSON file and at client side json file data will be display under pop up modal.

And once JSON file data has been load under pop up bootstrap modal, then we can change data and by click on the edit button, it will send Ajax request to PHP script and it will change JSON file data.

index.php

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <link href="https://cdn.datatables.net/1.12.0/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/dataTables.bootstrap5.min.js"></script>

        <title>PHP CRUD Operations with JSON File</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-4 mb-4 text-center text-warning">JSON CRUD operations in PHP | Update or Edit Data using Bootstrap Modal</h1>

            <span id="message"></span>
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-sm-9">Sample Data</div>
                        <div class="col col-sm-3">
                            <button type="button" id="add_data" class="btn btn-success btn-sm float-end">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered" id="sample_data">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Gender</th>
                                    <th>Age</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

<div class="modal" tabindex="-1" id="action_modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="sample_form">
                <div class="modal-header">
                    <h5 class="modal-title" id="dynamic_modal_title"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">First Name</label>
                        <input type="text" name="first_name" id="first_name" class="form-control" />
                        <span id="first_name_error" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Last Name</label>
                        <input type="text" name="last_name" id="last_name" class="form-control" />
                        <span id="last_name_error" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <select name="gender" id="gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Age</label>
                        <input type="number" name="age" id="age" class="form-control" />
                        <span id="age_error" class="text-danger"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="id" id="id" />
                    <input type="hidden" name="action" id="action" value="Add" />
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary" id="action_button">Add</button>
                </div>
            </form>
        </div>
    </div>
</div>



<script>

$(document).ready(function(){

    load_data();

    function load_data()
    {
        var seconds = new Date() / 1000;

        $.getJSON("data.json?"+seconds+"", function(data){

            data.sort(function(a,b){

                return b.id - a.id;

            });

            var data_arr = [];

            for(var count = 0; count < data.length; count++)
            {
                var sub_array = {
                    'first_name' : data[count].first_name,
                    'last_name' : data[count].last_name,
                    'gender' : data[count].gender,
                    'age' : data[count].age,
                    'action' : '<button type="button" class="btn btn-warning btn-sm edit" data-id="'+data[count].id+'">Edit</button>'
                };

                data_arr.push(sub_array);
            }

            $('#sample_data').DataTable({
                data : data_arr,
                order : [],
                columns : [
                    { data : "first_name" },
                    { data : "last_name" },
                    { data : "gender" },
                    { data : "age" },
                    { data : "action" }
                ]
            });

        });
    }

    $('#add_data').click(function(){

        $('#dynamic_modal_title').text('Add Data');

        $('#sample_form')[0].reset();

        $('#action').val('Add');

        $('#action_button').text('Add');

        $('.text-danger').text('');

        $('#action_modal').modal('show');

    });

    $('#sample_form').on('submit', function(event){

        event.preventDefault();

        $.ajax({
            url:"action.php",
            method:"POST",
            data:$('#sample_form').serialize(),
            dataType:"JSON",
            beforeSend:function()
            {
                $('#action_button').attr('disabled', 'disabled');
            },
            success:function(data)
            {
                $('#action_button').attr('disabled', false);
                if(data.error)
                {
                    if(data.error.first_name_error)
                    {
                        $('#first_name_error').text(data.error.first_name_error);
                    }
                    if(data.error.last_name_error)
                    {
                        $('#last_name_error').text(data.error.last_name_error);
                    }
                    if(data.error.age_error)
                    {
                        $('#age_error').text(data.error.age_error);
                    }
                }
                else
                {
                    $('#message').html('<div class="alert alert-success">'+data.success+'</div>');

                    $('#action_modal').modal('hide');

                    $('#sample_data').DataTable().destroy();

                    load_data();

                    setTimeout(function(){
                        $('#message').html('');
                    }, 5000);
                }
            }
        });

    });

    $(document).on('click', '.edit', function(){

        var id = $(this).data('id');

        $('#dynamic_modal_title').text('Edit Data');

        $('#action').val('Edit');

        $('#action_button').text('Edit');

        $('.text-danger').text('');

        $('#action_modal').modal('show');

        $.ajax({
            url:"action.php",
            method:"POST",
            data:{id:id, action:'fetch_single'},
            dataType:"JSON",
            success:function(data)
            {
                $('#first_name').val(data.first_name);
                $('#last_name').val(data.last_name);
                $('#gender').val(data.gender);
                $('#age').val(data.age);
                $('#id').val(data.id);
            }
        });

    });

});

</script>


action.php

<?php

//action.php

if(isset($_POST["action"]))
{
	$file = 'data.json';

	if($_POST['action'] == 'Add' ||$_POST['action'] == 'Edit')
	{
		$error = array();

		$data = array();

		$data['id'] = time();

		if(empty($_POST['first_name']))
		{
			$error['first_name_error'] = 'First Name is Required';
		}
		else
		{
			$data['first_name'] = trim($_POST['first_name']);
		}

		if(empty($_POST['last_name']))
		{
			$error['last_name_error'] = 'Last Name is Required';
		}
		else
		{
			$data['last_name'] = trim($_POST['last_name']);
		}

		$data['gender'] = trim($_POST['gender']);

		if(empty($_POST['age']))
		{
			$error['age_error'] = 'Age is required';
		}
		else
		{
			$data['age'] = trim($_POST['age']);
		}

		if(count($error) > 0)
		{
			$output = array(
				'error'		=>	$error
			);
		}
		else
		{
			$file_data = json_decode(file_get_contents($file), true);

			if($_POST['action'] == 'Add')
			{

				$file_data[] = $data;

				file_put_contents($file, json_encode($file_data));

				$output = array(
					'success' => 'Data Added'
				);
			}

			if($_POST['action'] == 'Edit')
			{
				$key = array_search($_POST['id'], array_column($file_data, 'id'));

				$file_data[$key]['first_name'] = $data['first_name'];

				$file_data[$key]['last_name'] = $data['last_name'];

				$file_data[$key]['age'] = $data['age'];

				$file_data[$key]['gender'] = $data['gender'];

				file_put_contents($file, json_encode($file_data));

				$output = array(
					'success' => 'Data Edited'
				);
			}
		}

		echo json_encode($output);
	}

	if($_POST['action'] == 'fetch_single')
	{
		$file_data = json_decode(file_get_contents($file), true);

		$key = array_search($_POST["id"], array_column($file_data, 'id'));

		echo json_encode($file_data[$key]);
	}
}

?>


Step 4 - Delete or Remove Data from JSON File


In PHP CRUD Operation with JSON file, here only Delete Operation is remaining and in this step you can find how to delete or remove data from JSON file using PHP Script.

So for delete JSON file data, first we will create Delete button in each row of data. So by click on this button, we can delete or remove data JSON file data.

After this, we will write jQuery code with Ajax request. So when we have click on delete button, then Ajax request will be send to PHP Script for Remove Data from JSON file using PHP Script.

At the PHP Script, first it has get data from JSON file and then after it will get key index number of Array and by using PHP unset() function array data will be remove and remaining data will be again write in JSON file using file_put_contents() function.

index.php

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <link href="https://cdn.datatables.net/1.12.0/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>

        <script src="https://cdn.datatables.net/1.12.0/js/dataTables.bootstrap5.min.js"></script>

        <title>PHP CRUD Operations with JSON File</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-4 mb-4 text-center text-primary">JSON CRUD operations in PHP | Delete or Remove Data from JSON File</h1>
            <span id="message"></span>
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-sm-9">Sample Data</div>
                        <div class="col col-sm-3">
                            <button type="button" id="add_data" class="btn btn-success btn-sm float-end">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered" id="sample_data">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Gender</th>
                                    <th>Age</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

<div class="modal" tabindex="-1" id="action_modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="sample_form">
                <div class="modal-header">
                    <h5 class="modal-title" id="dynamic_modal_title">Add Data</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">First Name</label>
                        <input type="text" name="first_name" id="first_name" class="form-control" />
                        <span id="first_name_error" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Last Name</label>
                        <input type="text" name="last_name" id="last_name" class="form-control" />
                        <span id="last_name_error" class="text-danger"></span>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <select name="gender" id="gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Age</label>
                        <input type="number" name="age" id="age" class="form-control" />
                        <span id="age_error" class="text-danger"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="id" id="id" value="" />
                    <input type="hidden" name="action" id="action" value="Add" />
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary" id="action_button">Add</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>

$(document).ready(function(){

    load_data();

    function load_data()
    {
        var seconds = new Date() / 1000;

        $.getJSON("data.json?"+seconds+"", function(data){

            data.sort(function (a, b) {
                return b.id - a.id
            });

            var data_arr = [];

            for(var count = 0; count < data.length; count++)
            {
                var sub_arr = {
                    'first_name' : data[count].first_name,
                    'last_name' : data[count].last_name,
                    'gender' : data[count].gender,
                    'age' : data[count].age,
                    'action' : '<button type="button" class="btn btn-warning btn-sm edit" data-id="'+data[count].id+'">Edit</button>&nbsp;<button type="button" class="btn btn-danger btn-sm delete" data-id="'+data[count].id+'">Delete</button>'
                };

                data_arr.push(sub_arr);
            }

            console.log(data_arr);

            $('#sample_data').DataTable({
                data:data_arr,
                order:[],
                columns: [
                    { data: "first_name" },
                    { data: "last_name" },
                    { data: "gender" },
                    { data: "age" },
                    { data: "action" },
                ]
            });

        });       

    }



    

    $('#add_data').click(function(){

        $('#dynamic_modal_title').text('Add Data');

        $('#sample_form')[0].reset();

        $('#action').val('Add');

        $('#action_button').text('Add');

        $('.text-danger').text('');

        $('#action_modal').modal('show');

    });

    $('#sample_form').on('submit', function(event){

        event.preventDefault();

        $.ajax({
            url:"action.php",
            method:"POST",
            data:$('#sample_form').serialize(),
            dataType:"JSON",
            beforeSend:function(){
                $('#action_button').attr('disabled','disabled');
            },
            success:function(data)
            {
                $('#action_button').attr('disabled',false);
                if(data.error)
                {
                    if(data.error.first_name_error)
                    {
                        $('#first_name_error').text(data.error.first_name_error);
                    }
                    if(data.error.last_name_error)
                    {
                        $('#last_name_error').text(data.error.last_name_error);
                    }

                    if(data.error.age_error)
                    {
                        $('#age_error').text(data.error.age_error);
                    }
                }
                else
                {
                    $('#message').html('<div class="alert alert-success">'+data.success+'</div>');
                    $('#action_modal').modal('hide');

                    $('#sample_data').DataTable().destroy();
                    
                    load_data();

                    setTimeout(function(){
                        $('#message').html('');
                    }, 5000);
                }
            }
        });

    });

    $(document).on('click', '.edit', function(){

        var id = $(this).data('id');

        $('#dynamic_modal_title').text('Edit Data');

        $('#action').val('Edit');

        $('#action_button').text('Edit');

        $('.text-danger').text('');

        $('#action_modal').modal('show');

        $.ajax({
            url:"action.php",
            method:"POST",
            data:{id:id, action:'fetch_single'},
            dataType:"JSON",
            success:function(data)
            {
                $('#first_name').val(data.first_name);
                $('#last_name').val(data.last_name);
                $('#gender').val(data.gender);
                $('#age').val(data.age);
                $('#id').val(data.id);
            }
        });

    });

    $(document).on('click', '.delete', function(){

        var id = $(this).data('id');

        if(confirm("Are you sure you want to delete this data?"))
        {
            $.ajax({
                url:"action.php",
                method:"POST",
                data:{action:'delete', id:id},
                dataType:"JSON",
                success:function(data)
                {
                    $('#message').html('<div class="alert alert-success">'+data.success+'</div>');

                    $('#sample_data').DataTable().destroy();

                    load_data();

                    setTimeout(function(){
                        $('#message').html('');
                    }, 5000);
                }
            });
        }

    });


});

</script>


action.php

<?php

//action.php

if(isset($_POST['action']))
{
	$file = 'data.json';
	
	/*if($_POST['action'] == 'fetch_all')
	{
		$file_data = file_get_contents($file);

		$data = json_decode($file_data, true);

		$output = array();

		if(count($data) > 0)
		{
			$id_data = array_column($data, 'id');

			array_multisort($id_data, SORT_DESC, $data);

			foreach($data as $row)
			{
				$sub_array = array();

				$sub_array[] = $row['first_name'];

				$sub_array[] = $row['last_name'];

				$sub_array[] = $row['gender'];

				$sub_array[] = $row['age'];

				$sub_array[] = '<button type="button" class="btn btn-warning btn-sm edit" data-id="'.$row["id"].'">Edit</button>&nbsp;<button type="delete" class="btn btn-danger btn-sm delete" data-id="'.$row["id"].'">Delete</button>';

				$output[] = $sub_array;
			}
		}

		$response = array(
			"draw"				=>	intval($_POST["draw"]),
			"recordsTotal"		=> 	count($data),
			"recordsFiltered"	=>	count($data),
			"data"				=>	$output
		);

		echo json_encode($response);
	}*/

	if($_POST['action'] == 'Add' || $_POST['action'] == 'Edit')
	{
		$error = array();

		$data = array();

		$data['id']	= time();

		if(empty($_POST['first_name']))
		{
			$error['first_name_error'] = 'First Name is Required';
		}
		else
		{
			$data['first_name'] = trim($_POST['first_name']);
		}

		if(empty($_POST['last_name']))
		{
			$error['last_name_error'] = 'Last Name is Required';
		}
		else
		{
			$data['last_name'] = trim($_POST['last_name']);
		}

		$data['gender'] = trim($_POST['gender']);

		if(empty($_POST['age']))
		{
			$error['age_error'] = 'Age is required';
		}
		else
		{
			$data['age'] = trim($_POST['age']);
		}

		if(count($error) > 0)
		{
			$output = array(
				'error'		=>	$error
			);
		}
		else
		{
			if($_POST['action'] == 'Add')
			{
				$file_data = json_decode(file_get_contents($file), true);

				//print_r($file_data);

				$file_data[] = $data;

				file_put_contents($file, json_encode($file_data));
				$output = array(
					'success'	=>	'Data Added'
				);
			}

			if($_POST['action'] == 'Edit')
			{
				$file_data = json_decode(file_get_contents($file), true);

				$key = array_search($_POST['id'], array_column($file_data, 'id'));

				$file_data[$key]['first_name'] = $data['first_name'];
				$file_data[$key]['last_name'] = $data['last_name'];
				$file_data[$key]['age'] = $data['age'];
				$file_data[$key]['gender'] = $data['gender'];

				file_put_contents($file, json_encode($file_data));

				$output = array(
					'success'	=>	'Data Edited'
				);

			}
		}

		echo json_encode($output);
	}

	if($_POST['action'] == 'fetch_single')
	{
		$file_data = json_decode(file_get_contents($file), true);

		$key = array_search($_POST['id'], array_column($file_data, 'id'));

		echo json_encode($file_data[$key]);
	}

	if($_POST['action'] == 'delete')
	{
		$file_data = json_decode(file_get_contents($file), true);

		$key = array_search($_POST['id'], array_column($file_data, 'id'));

		unset($file_data[$key]);

		file_put_contents($file, json_encode($file_data));

		echo json_encode(['success' => 'Data Deleted']);
	}
}

?>


So this PHP CRUD Operation with JSON file tutorial will help you if you have manage small data and if you not use any database for store data, then at that time JSON file is the best option for store data. So This tutorial will help for Insert, Update, Delete and Fetch Data from JSON file by using PHP with Ajax jQuery and Bootstrap Modal.







0 comments:

Post a Comment