How do I make a php page to load in background?
#6

Here is js code, you put this in your main js, or inside <script> tags on index (main) file.
Just replace "PUT_YOUR_URL_HERE" with your url

After request is finished successfully your data will be stored in "window.API_DATA"

NOTE: API Must return proper JSON format
NOTE: ES6 is supported on most current generation browsers, you can checkout compatibility table here

PHP код:
'use strict'
const API_ENDPOINT 'PUT_YOUR_URL_HERE';
(() => {
    const 
STATUS = {
        
OK200
    
};
    const 
ERROR = {
        
NONE'NONE',
        
PARSE'INVALID_JSON',
        
STATUS'INVALID_STATUS_CODE'
    
};
    const 
loadData = (urldata = {}) => {
        return new 
Promise((resolvereject) => {
            const 
xhr = new XMLHttpRequest();
            
// Using traditional function definition
            // to prevent invalid context (this)
            
xhr.onreadystatechange = function () {
                if (
XMLHttpRequest.DONE !== this.readyState) {
                    
// Not resolving nor rejecting as we need this promise to be done when request is
                    
return;
                }
                if (
STATUS.OK !== this.status) {
                    
// In case that status code is not 200 (OK) we assume something went wrong
                    
return reject({ errorERROR.STATUSurl });
                }
                
let data;
                try {
                    
data JSON.parse(this.responseText);
                } catch (
error) {
                    
// In case that server response was not valid json
                    // we reject this promise with proper error
                    
return reject({ errorERROR.PARSEresponsethis.responseTexturl });
                }
                return 
resolve({ errorERROR.NONEdata });
            };
            
xhr.open('GET'urltrue);
            
xhr.send();
        });
    };
    
window.onload = () => {
        
loadData(API_ENDPOINT)
            .
then((data) => { window.API_DATA data; })
            .catch((
error) => { console.error(error); });
    };
})(); 
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)