Category Archive JavaScript

Byphunsanit

jQuery: Ajax Cache

ต้องการเก็บข้อมูลส่วนที่ใช้บ่อยๆ ไว้ในฝั่ง user (browser) นั่นละ จะได้ลดการ query แต่ข้อมูลมันมีการเปลี่ยนแปลงด้วย ที่เก็บข้อมูลระยะยาวได้ในฝั่ง browser กลับออกแบบให้ localStorage เก็บข้อมูลถาวรโดยไม่มีการ expires เหมือน cookie ทำให้ต้องเขียน code จัดการเพิ่ม

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Ajax: localStorage</title>
</head>

<body>
    <h1>localStorage</h1>
    <div class="col-sm-12" id="datasA"></div>
    <div class="col-sm-12" id="resultA"></div>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script>
        $(function() {

            function getDatas() {
                let cacheKey = 'memories';

                if (cacheKey in localStorage) {
                    let datas = JSON.parse(localStorage.getItem(cacheKey));

                    // if expired
                    if (datas['expires'] < Date.now()) {
                        localStorage.removeItem(cacheKey);

                        getDatas()
                    } else {
                        setDatas(datas);
                    }
                } else {
                    $.ajax({
                        "dataType": "json",
                        "success": function(datas, textStatus, jqXHR) {
                            let today = new Date();

                            datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days

                            setDatas(datas);

                            localStorage.setItem(cacheKey, JSON.stringify(datas));
                        },
                        "url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",
                    });
                }
            }

            function setDatas(datas) {
                // display json as text
                $('#datasA').text(JSON.stringify(datas));

                // your code here
                let html = '';
                $.each(datas.datas, function(index, value) {
                    html += '<br>' + index + ' = ' + value;
                });
                $('#resultA').html(html);

            }

            // call
            getDatas();

        });
    </script>
</body>

</html>

ข้อมูลที่ call ผ่าน ajax จะโดนเก็บใน localStorage แต่เวลาใช้ก็จะเอามาเทียบ expires ก่อน ถ้ายังไม่หมดอายุก็เอามาใช้ ถ้าหมดอายุไปแล้วก็ call ใหม่ ลองดัดแปลงดูให้เหมาะกับงานดูครับ

Byphunsanit

Laravel: mix

มันคือ webpack ที่อธิบายง่าย ๆ คือ การ pack รวมเอา css, js มาไว้เป็นไฟล์เดียว หรือแค่ไฟล์ 4 ไฟล์ แทนที่จะโหลด css โหลด javascript หลาย ๆ ไฟล์ทำให้เว็บเราโหลดเร็วขึ้นเยอะเลย

เพราะว่าต้องใช้ npm ในการทำงานแนะนำว่าให้ทำตาม npm: ‘cross-env’ Is Not Recognized as an Internal or External Command ก่อนเพื่อป้องกันปัญหาที่จะเกินขึ้น

เริ่มจากการเพิ่ม package ที่จะใช้ใน command line ก่อนเช่น

  • npm i @fortawesome/fontawesome-free
  • npm i datatables
  • npm i icheck-bootstrap
  • npm i jquery
  • npm i jquery-ui
  • npm i moment
  • npm i numeral
  • npm i overlayscrollbars
  • npm i sweetalert2

เพิ่มโค้ทในไฟล์ /resources/js/bootstrap.js และเพิ่มโค้ทในไฟล์ /resources/sass/app.scss ตามคู่มือ 6.9 Laravel Mix

run command
npm run production
จะมีไฟล์เพิ่มมาใน /public/css/app.css และ /public/js/app.js

แก้ config AdminLte ให้ใช้ mix โดยเปิดไฟล์ /config/adminlte.php เปลี่ยน ‘enabled_laravel_mix’ => false, เป็น ‘enabled_laravel_mix’ => true,

จากนั้นลองใช้งานเว็บและ view source ดูจะเห็นว่าส่วนที่โหลด css และ javascript จะหายไปเยอะเลย

Byphunsanit

npm: ‘cross-env’ Is Not Recognized as an Internal or External Command

ใช้ npm แล้วมี error ‘cross-env’ Is Not Recognized as an Internal or External Command ทุกครั้ง ทั้งๆ ที่ทำตามคู่มือทุกอย่าง

วิธีแก้

  1. ลบโพลเดอร์ node_modules
  2. ลบไฟล์ package-lock.json
  3. เปิด command prompt โดยใช้ Run as administrator
  4. ใช้คำสั่ง npm install
  5. ทดสอบโดยใช้คำสั่ง npm run dev

หลังจากนี้ สามารถใช้ npm ได้ตามปกติแล้ว

Byphunsanit

Fetch API: Download

ที่นี้มาถึงการที่ใช้ fetch download file จาก server ซึ่งวิธีนี้ง่ายกว่าการใช้ jQuery ดึงไฟล์มามาก จากที่เคยเขียน jQuery ajax download file เอาไว้จะเห็นว่าวิธีนี้ง่ายกว่ามาก

เริ่มจากการที่โหลด download.js มาก่อน โดยใช้คำสั่ง npm i downloadjs
ไฟล์กลางที่ไว้ใช้ร่วมกัน

scripts.js

/*
pitt phunsanit
default fetch api options
version 1
*/
let fetchOptions = {
    "headers": {
        'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    "method": "post"
};

/*
pitt phunsanit
get file name from fetch api
version 1
*/
function fetchGetFilename(response) {
    let filename = '';
    let disposition = response.headers.get('Content-Disposition');
    if (disposition && disposition.indexOf('attachment') !== -1) {
        let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        let matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
        }
    }
    return filename;
}

/*
pitt phunsanit
get status from fetch api
version 1
*/
function fetchStatus(Response) {
    if (Response.status >= 200 && Response.status < 300) {
        return Promise.resolve(Response);
    } else {
        return Promise.reject(new Error(Response.status + ' : ' + Response.statusText));
    }
}

ตัวอย่างการใช้ fetch download file โดยใช้ downloadjs ช่วยให้ทำงานได้ทุกบราวเซอร์ (ยกเว้น IE ถ้าจะใช้กลับไปอ่าน Fetch API)

JavaScript/fetch.download.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

      <meta name="author" content="Pitt Phunsanit">
      <title>fetch: download</title>
   </head>
   <body>
      <script src="../node_modules/downloadjs/download.min.js"></script>
      <script src="../scripts.js"></script>
      <script>
fetchOptions.body = 'file=ISO 3166-1 two aplha COUNTRY codes (01102009).xls&token=HH89VOiirgXlCdEqDrFs';

fetch('http://localhost/snippets/PHP/download.php', fetchOptions)
    .then(fetchStatus)
    .then(
        function(response) {
            if (response.ok) {
                let fileName = fetchGetFilename(response);
                let mimeType = response.headers.get('Content-Type');

                response.blob().then(function(blob) {
                    download(blob, fileName, mimeType);
                });
            }
        }
    )
    .catch(function(error) {
        alert(error);
    });
      </script>

</body></html>

อ่านเพิ่มเติม

Byphunsanit

Fetch API

Fetch API เป็นวิธีที่ใช้ทำ ajax แทน XMLHttpRequest (XHR) สามารถใช้ได้กับทุกบราวเซอร์ยกเว้น อ้ายอี (IE) แม้แต่ microsoft edge ก็ยังใช้ได้ แต่จริงๆ แล้วสามารถบังคับให้อ้ายอีใช้ได้โดยการเรียกใช้ github/fetch ช่วย

ไฟล์กลางที่ไว้ใช้ร่วมกัน

scripts.js

/*
pitt phunsanit
default fetch api options
version 1
*/
let fetchOptions = {
    "headers": {
        'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    "method": "post"
};

/*
pitt phunsanit
get status from fetch api
version 1
*/
function fetchStatus(Response) {
    if (Response.status >= 200 && Response.status < 300) {
        return Promise.resolve(Response);
    } else {
        return Promise.reject(new Error(Response.status + ' : ' + Response.statusText));
    }
}

ตัวอย่างการใช้ fetch แบบ GET

JavaScript/fetch.get.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

      <meta name="author" content="Pitt Phunsanit">
      <title>fetch: get</title>
   </head>
   <body>
      <script src="../scripts.js"></script>
      <script>
fetch('http://localhost/snippets/PHP/json.json_encode.php?name=pitt&surname=phunsanit')
    .then(fetchStatus)
    .then(
        function(response) {

            response.json()
                .then(function(data) {
                    alert(JSON.stringify(data));
                });

        }
    )
    .catch(function(error) {
        alert(error);
    });
      </script>

</body></html>

เมื่อต้องการส่งข้อมูลแบบ POST ก็เพิ่ม option ไปเล็กน้อย
ตัวอย่างการ fetch แบบ POST

JavaScript/fetch.post.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

      <meta name="author" content="Pitt Phunsanit">
      <title>fetch: post</title>
   </head>
   <body>
      <script src="../scripts.js"></script>
      <script>
fetchOptions.body = '[email protected]&name=pitt&surname=phunsanit';

fetch('http://localhost/snippets/PHP/json.json_encode.php', fetchOptions)
    .then(fetchStatus)
    .then(
        function(response) {

            response.json()
                .then(function(data) {
                    alert(JSON.stringify(data));
                });

        }
    )
    .catch(function(error) {
        alert(error);
    });
      </script>

</body></html>

อ่านเพิ่มเติม