Obtain an AJAX request and create a division only once

advertisements

Using JavaScript, how can I get an AJAX request and create div only once? As you can see in this example, the AJAX request is received everytime you click on the button, and the div is also created: http://jsfiddle.net/2uvms99o/

HTML:

<button onclick="test();">Press Me</button>

JavaScript:

function test() {
    $.ajax({
        url: 'https://storage.googleapis.com/maps-devrel/google.json',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function (data) {
            var div = document.createElement('div');
            div.innerHTML = 'This is a div!';
            document.body.appendChild(div);
        }
    });
}

Maybe there's a better way to do this rather than onclick?


I can understand your problem two ways, the first is:

How do I only create the <div> once?

To which I'd suggest that you test for the existence of the created <div> element in the success function, if it already exists then use it, if it doesn't exist then create it:

success: function (data) {

    // if the element with the id of 'ajaxResponse'
    // doesn't exist in the DOM:
    if (!document.getElementById('ajaxResponse')) {

        // we create the <div> element:
        var div = document.createElement('div');

        // give it the id that we're looking for:
        div.id = 'ajaxResponse';

        // append it to the document.body:
        document.body.appendChild(div);
    }

    // find the element we want to work with (the <div> we
    // created, above:
    var responseDiv = document.getElementById('ajaxResponse');

    // set its innerHTML:
    responseDiv.innerHTML = "This is a div.";
}

JS Fiddle demo;

The alternative is:

How can I prevent more than one ajax request being initiated?

To which I'd suggest that in the success function you simply disable the <button>:

success: function (data) {
    var div = document.createElement('div');
    div.innerHTML = 'This is a div!';
    document.body.appendChild(div);

    // using document.querySelector, with a CSS attribute-
    // selector to select the first button with an 'onclick'
    // attribute; obviously change this to a selector
    // appropriate for use-case. And we then set the
    // disabled state to true (to prevent subsequent interaction):
    document.querySelector('button[onclick]').disabled = true;
}

JS Fiddle demo.