MSK MSK - 5 months ago 8
jQuery Question

how to use ajax autocallback

I have one index page containing one input tag and one division, with one ajax function which gives me data from server.Problem:- 1)with single letter give me 3 record, after i add one more letter it work fine but when i delete on letter it give me another copy of that data means it print data 2times.please solve this.



<!-- My Ajax Function -->

function sendInfo() {
var compName = $('#compName').val();

if(compName != null) {
$.get(
'RoomReservationServlet?action=RoomReservation&processName=customerDetailJson',
{c_CompName : compName},
function(responseJson) {
if (responseJson != null) {
$('#spn_hint').fadeIn();
$.each( responseJson, function(key, value) {
$('#spn_hint').append('<li value=' + value['Com_Name'] + '>'+ value['Com_Name'] + '</li>');
});
} else {
alert("Jason : Empty");
}
});
} else if(compName == null) {
alert("exit");
$('#spn_hint').fadeOut();
}
}

<!-- My html code -->

<label for="number">Company Name</label>
<input type="text" class="form-control" id="compName" placeholder="Company Name" required style="overflow:scroll; " onkeyup="sendInfo();">
<div id="spn_hint" style="display:none;position:absolute;"></div>




Answer

You could clear the div before appending to it:

if (responseJson != null) {  
    $('#spn_hint').empty(); //Clears all child elements so that you can start fresh
    $('#spn_hint').fadeIn();
    $ .each( responseJson, function(key, value) {
         $('#spn_hint').append('<li value=' + value['Com_Name'] + '>'+ value['Com_Name']    + '</li>');                                                                     
    });  
}
Comments