Search code examples
phpmysqlwindows-services

Run Php script constantly and if connected to internet as windows service which inserts data into xampp server


I am developing a desktop app which will store data offline but whenever the desktop gets a connection a php script should detect it (cron job) and upload it to the online server like this:

while(true){
    if(connected == true){
        // run code;
    else{
        // wait to get connection
    }
}

Solution

  • Hi Zaki Muhammad Mulla,

    I did some testing myself, and I came up with the following piece of code
    Running the code snippets here won't work because this is a sandbox and there is no access to the localstorage here.

    Make sure to include Jquery in your code

    <script  
    src="https://code.jquery.com/jquery-3.4.1.js" 
    integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
    crossorigin="anonymous">
    </script>

    Then the actual function that will do the trick:

    function processData(online){
            if(online == true){
                //My connection is online so I can execute code here
                        //If data is stored locally, read it and post it with an $.ajax POST
                        //I can loop through all the data and insert it per found row of data
                            for(var i=0, len=localStorage.length; i<len; i++) {
                                var key = localStorage.key(i);
                                var value = localStorage[key];
                                    $.ajax({  
                                    type: 'POST',  
                                    url: 'PATH/TO/SCRIPT.php', 
                                    data: { column: key, value: value },
                                    success: function(response) {
                                        //The insert was succesful
                                        content.html(response);
                                    }
                                   });
                            }
                                
            }else{
                //Create your own loop here and fill data accordingly
                for(i = 0; i < 12; i++){
                    localStorage.setItem("lastname" + i, "Smith");
                    localStorage.setItem("firstname" + i, "John");
                    localStorage.setItem("age" + i, "22");
                    localStorage.setItem("job" + i, "Developer");    
                }
            }
        }

    And at last the window.setInterval() to run a function every x seconds (Keep in mind 1 second = 1000 in the settimeout)

    <script>
    window.setInterval(function(){
            var online = navigator.onLine;
            processData(online);
        }, 1000);
    </script>

    Hope this may help you on your quest!
    The sources I used: