Kamis, 31 Desember 2020

Get Date of 1 month Ago with PHP

 Hi again, at the first day of the year 2021 I wrote this post since my web app showed error while retrieving data between the date of one month ago until today. 

So here is the way to get date of 1 month Ago.

	
    	$dateHelp = date("Y-m-d");
        $monthAgo = Date("Y-m-d", strtotime($dateHelp."-1 Month"));
    


To get the date of  N months later / ago, just change the text "-1 Month" to "+N Month" to get N months later or "-N Month" to get N months ago.

Here is the source where I read the solution. Source

Minggu, 30 Agustus 2020

Save PNG image from HTML5 Canvas (the correct way, proved working!!)

This post is kind of a continuation of my previous post 'Take A Picture From Webcam With HTML5'. I had then an issue how to save the image localy. The image taken from the webcam is saved in base64 encoded data with this format data:image/png;base64,AAAFBfj....[base64 encoded data]

After I googled around, the most solution that I found told me just seperate the base64 data from that format and decode it directly to save the image. Unfortunately, its not that easy!!!

shortly, I'll show you how to do it correctly. This solution is shown here. Thanks mas bro Fazlurr!! you are the best.

again, I developed the application using Codeigniter and the code I show here is the function to save the image localy. This function is called by an AJAX function. 



function saveImage(){
     $img = str_replace('data:image/png;base64,', '', $_POST['data']);
     $img = str_replace(' ', '+', $img);
     $data = base64_decode($img);
     $file = FCPATH.'/image/page/'.$_POST['name'].'.png';
     $success = file_put_contents($file, $data);
     echo $success ? '1' : '0';
}



the AJAX send  two POST data; the image data taken from canva and the name used for this image. Take a look at the third line, this line is the key. Other solutions found in google don't have this line, so most of them failed to save the image correctly. 

Well, the funny thing is that I know it works but I don't know what does that third line do, so dont ask me why this code works...ehehehe....

Kamis, 16 Juli 2020

scrollbar Bootstrap Modal

The real tittle is actually "how to make second shown Modal scrollbar". I have two modal on one page. The second modal should be shown as the result of ajax response sent in the first modal, so the first modal will be hidden and followed by showing the second modal. The second modal has a length, that it needs to be scrolled up and down. The problem was the scrollbar does not work for that modal, instead the scrollbar was functionable for the parent page.

So here is the solution:

 

<div class="modal fade" id="myModal"  role="dialog" aria-hidden="true" style="overflow-y: initial !important">
    <div class="modal-xl modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                ...
            </div>
            <div class="modal-body" >
                ... 
            </div>

        </div>
    </div>
</div>


Take a look at style="overflow-y: initial !important". This is the solution.

Select2 problem in Bootstrap Modal

Its a common problem implementing select2 in Bootstrap Modal. Mostly you will face problem that either the dropdown menu shown behind the modal or the livesearch doesn't work.

I found the solution after I browsed around, unfortunately I forgot the source where I found this solution. What I remembered, blurly, I found it in Github.

So, if my HTML Bootstrap Modal looks like this:

 
<div class="modal fade" id="myModal"  role="dialog" aria-hidden="true">
    <div class="modal-xl modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                ...
            </div>
            <div class="modal-body" >
                <div class="form-group">
                    <label for="idMySelect">SELECT</label>
                    <select id="idMySelect" class="form-control basic">
                        <option value="one">option one</option>
                        <option value="two">option two</option>
                        <option value="three">option three</option>
                        ...
                    </select>
                </div> 
            </div>

        </div>
    </div>
</div>


the JS for select2 in that modal would be:

 
$("#idMySelect").select2({
     tags: true,
     dropdownParent: $('#myModal')
});

We should set each select2 separately, if we have more than one select2 and especially if those select2 are in different modal (if we use more modals in one page) or some are on the parent page.

Selasa, 14 Juli 2020

Take Picture From Webcam With HTML 5

HTML5 has a super cool feature, that enables us to access the media installed in our PC. During developing a web app, I surprised with two things, which are already wellknown for most people maybe. But for me they are new and its really good to know.

My app has to take pictures and save them as PDF, but those pictures should not be saved. So first thing, here is my code to take pictures from a web using a webcam.

Here are my sources. Sumber 1 dan Sumber 2

HTML

 
<style>
.videoElement {
 width: 400px;
 height: 275px;
 background-color: #666;
    transform: rotateY(180deg);
    -webkit-transform:rotateY(180deg); /* Safari and Chrome */
    -moz-transform:rotateY(180deg); /* Firefox */
}
</style>

<video autoplay="true" id="video-webcam" class="videoElement" style="text-align:center">
   Izinkan untuk Mengakses Webcam untuk Demo
</video>


<img id="snapshot" style="width: 400px;height: 275px;">                          

<button onclick="takeSnapshot()"> Take Picture </button>
                            


And here is the JS code:

 
var video = document.querySelector("#video-webcam");

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

if (navigator.getUserMedia) {
    navigator.getUserMedia({ video: true }, handleVideo, videoError);
}

function handleVideo(stream) {
    video.srcObject = stream;
    //console.log(stream);
}

function videoError(e) {
    // do something
    alert("Izinkan menggunakan webcam untuk demo!")
}

function takeSnapshot() {
    var img = document.getElementById('snapshot');
    var context;
    var width = video.offsetWidth
            , height = video.offsetHeight;

    canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, width, height);

    img.src = canvas.toDataURL('image/png');
    img.style="transform: scaleX(-1);width: 400px;height: 275px";

}


What I learnt from that code are:
  1. The display taken from webcam has to be mirrored, as well as the picture taken. I did it with the CSS above.
  2. The images, that are taken using canva, are saved in Base64 code. This is super cool, furthermore the HTML tag is able to show an image with source of Base64 code. Super cool.... this feature helps me a lot, because I don't have to save the picture in server. What I did was I took this Base64 code and put them in HTML tag, which the HTML code is later converted to PDF file

Thats all, folks

Sabtu, 13 Juni 2020

Transparent Background (Modal Loader)

Quick post. I want to show a loader, that block the whole page and it should not be closeable, while waiting for AJAX response. I use modal and loader image then I set the modal background to transparent.

To do it, I read from this link_1 and link_2.


 
<div class="modal fade" id="loaderModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content" style="background-color:rgba(0, 0, 0, 0.0);">
            <div class="modal-body">
                //replace with gif loader image
                <div class="loader dual-loader mx-auto"></div>
                <div class="row">
                    <div class="col-xl-12 col-md-12 col-sm-12 col-12" style="text-align:center; color:black">Loading...</div>
                </div>
            </div>
        </div>
    </div>
</div>

Jumat, 12 Juni 2020

Javascript konversi angka ke format rupiah

thanks to faisalman  who provides this incredible javascript. 
Javascript yg membantu kita mengkonversi angka ke format rupiah dan sebaliknya, script yg sangat membantu sekali. Recomended utk di bookmark. Ini linknya

PHP Set session timeout

Quick post. This post will help me to recall how to set a session timeout in PHP someday. Lets cut the explanation what is actually happening behind the scene in PHP for timing out the session. As my other posts, I will put the source where I read this great and helpfull solution. Link. I'd like to thank the dude who wrote that post.

So, I'm still using CodeIgniter and I put this function on my Model for login. So here is my function:


    function session_timeout_check()
    {
        
        $timeout_max = 1800;//timeout after 30 minutes
        $time = $_SERVER['REQUEST_TIME'];

        if(isset($_SESSION['LAST_ACTIVITY']))
        {
            if($time - $_SESSION['LAST_ACTIVITY'] > $timeout_max)
            {
                return 1;
            }
            else
            {
                $_SESSION['LAST_ACTIVITY'] = $_SERVER['REQUEST_TIME'];
                return 0;
            }
        }
        else
        {
            return 1;
        }
    }

I put that function in the constructor of all controller:


    public function __construct()
    {    
        parent::__construct();
        $this->load->model(array("M_login"));
        session_start();
        if($this->M_login->session_timeout_check() == 1)
        {
            //unsetting session variable, destroying session and redirecting to login page
        }
    }

inside the if you can put other conditions to check the session.

so that's all folks.

Senin, 27 April 2020

AJAX in JQuery

Again, it is just a quick post that helps me recall something that I forget easily. Here is the syntax for AJAX in JQuery. I have seen 2 types of AJAX syntax in JQuery, for me this syntax is much easier to understand.


$.ajax({
            type:"POST",
            url:"urlToAjax.php",
            data:{
              "data1":dat,
              "data2":dat2 
            },
            success : function(results) {
              console.log(results)
              //any code if succeed goes here 
            },
            error : function(res){
              console.log(res)
              //any code to generate error report goes here
            }
  });


The code above sends Request using POST.

That's all folks.

Kamis, 09 April 2020

Creating JSON data in Javascript

Quick post about how to create JSON data in javascript.
I want to POST some inputs via AJAX but I want send them just in one variable, don't ask me why. I just want to do it that way.

here is my HTML code

<input id="name" type="text">

<input id="phone" type="text">

<input id="address" type="text">

I want send them as JSON data, here is how I do it:


var obj = new Object();
obj.name = document.getElementById('name').value;
obj.phone= document.getElementById('phone').value;
obj.address= document.getElementById('address').value;

var myData = JSON.stringify(obj);


That's it. the variable myData is the json data.