Hướng dẫn crud ajax modal php - crud ajax modal php

Trong mã này, chúng tôi sẽ chỉ cho bạn cách hiển thị dữ liệu với phương thức Bootstrap và cập nhật nó trong PHP & MySQL bằng AJAX. Chức năng này là một trong những chức năng quan trọng nhất khi tạo một ứng dụng. Vì vậy, chúng tôi hy vọng rằng bạn thấy nó hữu ích cho nghiên cứu của bạn.

Show

    Hiển thị hồ sơ cho phương thức Bootstrap của bạn với PHP đang giúp trải nghiệm người dùng không tải trang web của bạn.

    Index.html

    Đầu tiên, chúng ta cần tạo index.html của mình chỉ cần kiểm tra mã dưới đây.

    
    
    
      	Edit or Update Data Using PHP & MySQL Ajax
    
      	
    	
      	
      	
      	
    
      
    
       
    	


    Edit or Update Data Using PHP & MySQL Ajax



    Add New Employee

    List of Employees

    Save.php

    Sau mã trên để chúng tôi cần chức năng lưu để chúng tôi có thể cho phép chúng tôi thêm một bản ghi mới.

    connect_errno) {
    	  echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    	  exit();
    	}
    
    	// Set the INSERT SQL data
    	$sql = "INSERT INTO employees (email, first_name, last_name, address)
    	VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')";
    
    	// Process the query so that we will save the date of birth
    	if ($mysqli->query($sql)) {
    	  echo "Employee has been successfully created.";
    	} else {
    	  return "Error: " . $sql . "
    " . $mysqli->error; } // Close the connection after using it $mysqli->close(); ?>

    All.php

    Mã tiếp theo của chúng tôi là về việc nhận tất cả các hồ sơ thông qua AJAX.

    connect_errno) {
    	  echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    	  exit();
    	}
    
    	// Set the INSERT SQL data
    	$sql = "SELECT * FROM employees";
    
    	// Process the query so that we will save the date of birth
    	$results = $mysqli->query($sql);
    
    	// Fetch Associative array
    	$row = $results->fetch_all(MYSQLI_ASSOC);
    
    	// Free result set
    	$results->free_result();
    
    	// Close the connection after using it
    	$mysqli->close();
    
    	echo json_encode($row);
    ?>

    Get.php

    Trong mã này, chúng tôi sẽ nhận được bản ghi và hiển thị nó thông qua phương thức.

    connect_errno) {
    	  echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    	  exit();
    	}
    
    	// Set the INSERT SQL data
    	$sql = "SELECT * FROM employees WHERE id='".$employeeId."'";
    
    	// Process the query so that we will save the date of birth
    	$results = $mysqli->query($sql);
    
    	// Fetch Associative array
    	$row = $results->fetch_assoc();
    
    	// Free result set
    	$results->free_result();
    
    	// Close the connection after using it
    	$mysqli->close();
    
    	echo json_encode($row);
    ?>

    Update.php

    Bây giờ trong mã này, chúng tôi được bật để cập nhật bản ghi sau khi nhấp vào nút "Cập nhật" thông qua phương thức bằng AJAX.

    connect_errno) {
    	  echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    	  exit();
    	}
    
    	// Set the INSERT SQL data
    	$sql = "UPDATE employees SET email='".$email."', first_name='".$first_name."', last_name='".$last_name."', address='".$address."' WHERE id='".$id."'";
    
    	// Process the query so that we will save the date of birth
    	if ($mysqli->query($sql)) {
    	  echo "Employee has been sucessfully updated.";
    	} else {
    	  return "Error: " . $sql . "
    " . $mysqli->error; } // Close the connection after using it $mysqli->close(); ?>

    Scripts.js

    Trong mã này, chúng tôi được phép xử lý các mã PHP ở trên thông qua AJAX khỏi lưu bản ghi, nhận tất cả các bản ghi, truy xuất hồ sơ và cập nhật nó.

    
    function all() 
    {
    	// Ajax config
    	$.ajax({
            type: "GET", //we are using GET method to get all record from the server
            url: 'all.php', // get the route value
            success: function (response) {//once the request successfully process to the server side it will return result here
                
                // Parse the json result
            	response = JSON.parse(response);
    
                var html = "";
                // Check if there is available records
                if(response.length) {
                	html += '
    '; // Loop the parsed JSON $.each(response, function(key,value) { // Our employee list template html += ''; html += "

    " + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

    "; html += "

    " + value.address + "

    "; html += ""; html += '
    '; }); html += '
    '; } else { html += '
    '; html += 'No records found!'; html += '
    '; } // Insert the HTML Template and display all employee records $("#employees-list").html(html); } }); } function save() { $("#btnSubmit").on("click", function() { var $this = $(this); //submit button selector using ID var $caption = $this.html();// We store the html content of the submit button var form = "#form"; //defined the #form ID var formData = $(form).serializeArray(); //serialize the form into array var route = $(form).attr('action'); //get the route using attribute action // Ajax config $.ajax({ type: "POST", //we are using POST method to submit the data to the server side url: route, // get the route value data: formData, // our serialized array data for server side beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click $this.attr('disabled', true).html("Processing..."); }, success: function (response) {//once the request successfully process to the server side it will return result here $this.attr('disabled', false).html($caption); // Reload lists of employees all(); // We will display the result using alert alert(response); // Reset form resetForm(form); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // You can put something here if there is an error from submitted request } }); }); } function resetForm(selector) { $(selector)[0].reset(); } function get() { $(document).delegate("[data-target='#edit-employee-modal']", "click", function() { var employeeId = $(this).attr('data-id'); // Ajax config $.ajax({ type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: {employee_id:employeeId}, //set data beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click }, success: function (response) {//once the request successfully process to the server side it will return result here response = JSON.parse(response); $("#edit-form [name=\"id\"]").val(response.id); $("#edit-form [name=\"email\"]").val(response.email); $("#edit-form [name=\"first_name\"]").val(response.first_name); $("#edit-form [name=\"last_name\"]").val(response.last_name); $("#edit-form [name=\"address\"]").val(response.address); } }); }); } function update() { $("#btnUpdateSubmit").on("click", function() { var $this = $(this); //submit button selector using ID var $caption = $this.html();// We store the html content of the submit button var form = "#edit-form"; //defined the #form ID var formData = $(form).serializeArray(); //serialize the form into array var route = $(form).attr('action'); //get the route using attribute action // Ajax config $.ajax({ type: "POST", //we are using POST method to submit the data to the server side url: route, // get the route value data: formData, // our serialized array data for server side beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click $this.attr('disabled', true).html("Processing..."); }, success: function (response) {//once the request successfully process to the server side it will return result here $this.attr('disabled', false).html($caption); // Reload lists of employees all(); // We will display the result using alert alert(response); // Reset form resetForm(form); // Close modal $('#edit-employee-modal').modal('toggle'); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // You can put something here if there is an error from submitted request } }); }); } $(document).ready(function() { // Get all employee records all(); // Submit form using AJAX To Save Data save(); // Get the data and view to modal get(); // Updating the data update(); });

    Styles.css

    Sau đó, mã cuối cùng của chúng tôi về phong cách tùy chỉnh của trang của chúng tôi.

    .list-email {
    	font-style: italic;
    }
    
    .list-address {
    	margin-top: -14px;
        margin-bottom: 0px;
        font-size: 12px;
    }

    Được rồi, chúng tôi đã hoàn thành việc thiết lập mã của chúng tôi và giờ đây bạn có thể bật/chỉnh sửa bản ghi của mình bằng AJAX. Tôi hy vọng mã này có thể giúp bạn.

    Tải xuống

    Happy Codings :)