AJAX Simple

Discussion in 'JavaScript' started by Web_Dev_Chris, Jun 17, 2019.

  1. #1
    Hi,

    I’m trying to work out the simplest way to reuse AJAX in a project.

    This is what I have so far, would this work to reuse?

    //AJAX Variables
    var xhr = new XMLHttpRequest();
    var _success = xhr.status == 200;
    //AJAX Error Message
    function no_msg(element){
                    document.querySelector(element).innerHTML =
                    "Oops. We have encountered an error.";                           
    };
    document.querySelector("#btn")
      .addEventListener('click', function(){
                                  
                    xhr;
                    xhr.onload = function(){
                    if(_success){
                    h1.innerHTML = xhr.responseText;
                    }
                  
                    else{
                    no_msg("#text");
                    }
                  
                    };
                    xhr.open("GET", "data.txt", true);
                    xhr.send();
    });
    console.log(xhr);
    Code (JavaScript):
     
    Web_Dev_Chris, Jun 17, 2019 IP
  2. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #2
    Learned the hard way that this is not possible...
     
    Web_Dev_Chris, Jun 18, 2019 IP