Hướng dẫn update data without refresh page in php - cập nhật dữ liệu mà không cần làm mới trang trong php

Giả sử bạn muốn hiển thị một số nội dung nguồn cấp dữ liệu trực tiếp [giả sử livefeed.txt] trên trang web của bạn mà không cần làm mới trang thì ví dụ đơn giản hóa sau đây là dành cho bạn.live feed content [say livefeed.txt] on you web page without any page refresh then the following simplified example is for you.

Trong tệp HTML dưới đây, dữ liệu trực tiếp được cập nhật trên phần tử div của ID "Livingata"html file, the live data gets updated on the div element of id "liveData"

index.html




    Live Update
    
    

Loading Data...

Dưới đây autoupdate.js đọc dữ liệu trực tiếp bằng cách sử dụng đối tượng XMLHTTPREQUEST và cập nhật phần tử HTML Div trên 1 giây. Tôi đã đưa ra ý kiến ​​về hầu hết các phần của mã để hiểu rõ hơn.autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.

autoUpdate.js

window.addEventListener['load', function[]
{
    var xhr = null;

    getXmlHttpRequestObject = function[]
    {
        if[!xhr]
        {               
            // Create a new XMLHttpRequest object 
            xhr = new XMLHttpRequest[];
        }
        return xhr;
    };

    updateLiveData = function[]
    {
        var now = new Date[];
        // Date string is appended as a query with live data 
        // for not to use the cached version 
        var url = 'livefeed.txt?' + now.getTime[];
        xhr = getXmlHttpRequestObject[];
        xhr.onreadystatechange = evenHandler;
        // asynchronous requests
        xhr.open["GET", url, true];
        // Send the request over the network
        xhr.send[null];
    };

    updateLiveData[];

    function evenHandler[]
    {
        // Check response is ready or not
        if[xhr.readyState == 4 && xhr.status == 200]
        {
            dataDiv = document.getElementById['liveData'];
            // Set current data text
            dataDiv.innerHTML = xhr.responseText;
            // Update the live data every 1 sec
            setTimeout[updateLiveData[], 1000];
        }
    }
}];

Đối với mục đích thử nghiệm: Chỉ cần viết một số điều trong LiveFeed.txt - bạn sẽ được cập nhật tương tự trong index.html mà không cần làm mới.

livefeed.txt

Hello
World
blah..
blah..

Lưu ý: Bạn cần chạy mã trên trên máy chủ web [ví dụ: // localhost: 1234/index.html] không phải là tệp HTML của máy khách [ví dụ: tệp: /// c:/index.html]. You need to run the above code on the web server [ex: //localhost:1234/index.html] not as a client html file [ex: file:///C:/index.html].

Được gửi bởi Argie vào thứ Năm, ngày 28 tháng 1 năm 2021 - 11:46.

Xin chào mọi người, tính năng của hướng dẫn này là nó cho phép bạn lưu dữ liệu vào cơ sở dữ liệu và hiển thị dữ liệu từ cơ sở dữ liệu mà không làm mới trang. Tôi đã sử dụng AJAX và PHP trong hướng dẫn này. Mục tiêu của chúng tôi cho hướng dẫn này là tạo một ứng dụng web đơn giản có hình thức đơn giản sẽ dẫn đến việc tự động tải dữ liệu sau khi phản hồi thành công của việc lưu dữ liệu. Để bắt đầu mã hóa, hãy làm theo các bước được cung cấp dưới đây.

Requirements:

  • Tải xuống và cài đặt bất kỳ máy chủ web cục bộ nào như XAMPP/WAMP.

Bước 1: Tạo cơ sở dữ liệu của chúng tôi

Để tạo cơ sở dữ liệu:

  1. Nếu bạn đang sử dụng XAMPP/WAMP, hãy mở bảng điều khiển của XAMPP/WAMP và Strat "Apache" và "MySQL"."Apache" and "MySQL".
  2. Mở phpmyadmin trong trình duyệt web. [ // localhost/phpmyadmin]
  3. Tạo một cơ sở dữ liệu mới đặt tên "AJAXPHP".
  4. Sau khi tạo tên cơ sở dữ liệu, nhấp vào SQL và dán mã bên dưới.

Bước 2: Tạo biểu mẫu của chúng tôi

Trong đó, chúng tôi sẽ tạo biểu mẫu của chúng tôi hiển thị dữ liệu từ cơ sở dữ liệu. Để tạo biểu mẫu của chúng tôi, hãy sao chép mã bên dưới và lưu nó dưới dạng "index.php"."index.php".

  1. Save and load data without leaving the page using PHP and Ajax

  2. $[document].ready[function[] {

  3. //##### Add record when Add Record Button is click #########

  4. $["#content-form"].submit[function [e] {

  5. e.preventDefault[];

  6. if[$["#contentText"].val[]==='']

  7. {

  8. alert["Please enter some text!"];

  9. return false;

  10. }

  11. var myData = 'content_txt='+ $["#contentText"].val[]; //build a post data structure

  12. jQuery.ajax[{

  13. type: "POST", // Post / Get method

  14. url: "response.php", //Where form data is sent on submission

  15. dataType:"text", // Data type, HTML, json etc.

  16. data:myData, //Form variables

  17. success:function[response]{

  18. $["#responds"].append[response];

  19. $['#contentText'].val[""]

  20. },

  21. error:function [xhr, ajaxOptions, thrownError]{

  22. alert[thrownError];

  23. }

  24. }];

  25. }];

  26. }];

  27. .form_style #textarea {

  28. border: 1px solid #CCCCCC;

  29. }

  30. .form_style #FormSubmit {

  31. display: block;

  32. background: #003366;

  33. border: 1px solid #000066;

  34. color: #FFFFFF;

  35. margin-top: 5px;

  36. }

  37. #responds{

  38. margin: 0px;

  39. padding: 0px;

  40. list-style: none;

  41. width:100%;

  42. }

  43. #responds li{

  44. list-style: none;

  45. padding: 10px;

  46. background: #D1CFCE;

  47. margin-bottom: 5px;

  48. border-radius: 5px;

  49. font-family: arial;

  50. font-size: 13px;

  51. }

  52. .del_wrapper{float:right;}.content_wrapper {

  53. width: 500px;

  54. margin-right: auto;

  55. margin-left: auto;

  56. }

  57. .item-list{

  58. text-align: left;

  59. }

  60. #contentText{

  61. width: 100%;

  62. }

  63. Save and Load Data without leaving the page using PHP and Ajax


  64. Add record


  • Bước 3: Tạo kết nối cơ sở dữ liệu của chúng tôi

    Sao chép mã dưới đây và lưu nó dưới dạng "config.php"."config.php".

    Bước 4: Viết tập lệnh lưu của chúng tôi

    Trong bước này, chúng tôi viết mã lưu dữ liệu mà không cần tải trang. Sao chép mã dưới đây và lưu nó dưới dạng "Phản hồi.php"."response.php".

    1. Bài Viết Liên Quan

      Chủ Đề