Van icon

AJAX Local File

Links


    //AJAX check LOCAL FILE
    We create a txt file with the name sample.txt in the same Folder
    Also an html page with a button with some script 
    <button id="button">Get Text File</button>
    xh
    //Create event listener
        document.getElementById('button').addEventListener('click', loadText);

        function loadText(){
            // console.log('Button clicked');
            //create XHR Object
            var xhr = new XMLHttpRequest();
            // console.log(xhr); //this gives us the info of this method (first image)

            // OPEN - type, url/file, asyn
            xhr.open('GET', 'sample.txt', true); //type of method, url/file and if it is asynchronous or not
            console.log("READY STATE: ", xhr.readyState);
            xhr.onload = function(){
                console.log("READY STATE: ", xhr.readyState);
                if(this.status == 200){
                    console.log(this.responseText);
                    document.getElementById('text').innerHTML = this.responseText; //aƱadimos datos al tag que queramos
                }else if(this.status == 404){
                    document.getElementById('text').innerHTML = "not Found"; 
                }
            }
            //Control errors
            xhr.onerror = function(){
                console.log('Request Error');
            }
            // Sends request
            xhr.send(); //this is to give us the data of sample.txt, if not given we can check in network F12
        }

        // HTTP Statuses
        // 200: OK
        // 403: Forbidden
        // 404: Not Found

        Esquema EsquemaEsquema


    //Old way instead of xhr.onload*
    xhr.onreadystatechange = function(){
        console.log('READYSTATE:', xhr.readyState);
        if(this.readyState == 4 && this.satatus == 200){ //if 4 that's like 200
            console.log(this.responseText);
        }
    }
    // Values
    // readyState Values
    // 0: request not initialized
    // 1: server connection established
    // 2: request received
    // 3: processing request
    // 4: request finished and response is ready


    //OPTIONAL - used for loaders, 
    xhr.onprogress = function(){
        console.log("READY STATE: ", xhr.readyState);
    }