1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

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.
    SEMrush
    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
    SEMrush
  2. Web_Dev_Chris

    Web_Dev_Chris Active Member

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