Ibrahim İnce Ibrahim İnce - 2 months ago 12
Javascript Question

Showing loader.gif with getJSON

I want to use a loader gif while retrieving data through AJAX with getJSON. I have not found proper solution yet. I have used this

$("#loader").show();
and this
$("#loader").hide();
but its starts as soon as page loads. I want it to work when i click the search button.
Any suggestion will be highly appreciated.
Here is the my html codes:

<div class="container">
<div id="wrapper">
<section id="gallery">
<input type="text" id="KUNDE" placeholder="Search by name or ID." /> <di id="loader"><img src="loader.gif"/></di>
<button id="buton" type="button" class="btn-style" value="search" onclick="find();">Search</button>
<button id="button" class="btn-style">Clean Results</button>

</section>
<ul id="list"><li> </li> </ul>
</div>


Here is the my jquery codes:

<script>
$("#button").click(function (e) {
$("#list").find('li').remove();
});
$(function () {
$("#KUNDE").focus();
});
$(document).keypress(function (e) {
if (e.which == 13) {
$("#buton").click();
}
});
var uri = 'navisioncustomer.json';
function find() {
var info = $('#KUNDE').val();
$("#loader").show();
$.getJSON(uri)
.done(function (data) {
var item = data.filter(function (obj) {
return obj.name === info || obj.ID === info;
})[0];
if (typeof item !== 'undefined' || item !== null) {
$("#list").append("<li>ID = " + item.ID + "<br />Name = " + item.name + "<br />Phone = " + item.phone + "<br />Contact = " + item.contact + "<br />BalanceLCY = " + item.balanceLCY + "<br /> CreditLimitLCY = " + item.creditLimitLCY + "</li>");
}
})
.fail(function (jqXHR, textStatus, err) {
$('#KUNDE').text('Error: ' + err);
});
$("#loader").hide();
}
var options = {
url: "navisioncustomer.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options);
</script>

Answer

You could use the .always callback of JSON, read more on: http://api.jquery.com/jquery.getjson/

function find() {
    var info = $('#KUNDE').val();
    $("#loader").show();
    $.getJSON(uri)                
        .done(function (data) {
            var item = data.filter(function (obj) {
                return obj.name === info || obj.ID === info;
            })[0];
            if (typeof item !== 'undefined' || item !== null) {
                $("#list").append("<li>ID      = " + item.ID + "<br />Name    = " + item.name + "<br />Phone      = " + item.phone + "<br />Contact       = " + item.contact + "<br />BalanceLCY      = " + item.balanceLCY + "<br /> CreditLimitLCY       = " + item.creditLimitLCY + "</li>");
            }
        })               
        .fail(function (jqXHR, textStatus, err) {
            $('#KUNDE').text('Error: ' + err);
        })
        .always(function () { $("#loader").hide(); });
}

What your original code is saying show the loader > make request > hide the loader, and using callback to hide the loader will wait till the result