codever codever - 4 months ago 16
Javascript Question

How to Diplay "No result Found " in Autocomplete using $.getJSON

I want to show "No result Found " message when response is empty.In some case when back end session expired at that time it will return login page but i need json data so how can handle this html data .

$( "#customers_name" )
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "ajax_functions.php", {
term: extractLast( request.term ),
console: $('select[name="console"] option:selected').val(),
call: 'getCustomersEmailList',
nmsAdmin: '<?php echo tep_session_id();?>'
}, response );
},
change: function (event, ui) {
if(!ui.item){
$("#customers_name").val("");
}
},
focus: function() {

return false;
},
select: function( event, ui ) {
var customer_id = ui.item.customer_id;
var customer_email = ui.item.customerEmail;
console.log(ui);
$('#customer_id').val(customer_id);
$('#customer_email').val(customer_email);
var terms = split( this.value );

terms.pop();

terms.push( ui.item.value );

terms.push( "" );
this.value = terms.join( "" );
return false;
}
});

Answer

I have edited you code like below and working fine for me. Can you please check.

$( "#customers_name" )
  .bind( "keydown", function( event ) {
    if ( event.keyCode === $.ui.keyCode.TAB &&
        $( this ).autocomplete( "instance" ).menu.active ) {
      event.preventDefault();
    }
  })
  .autocomplete({
    source: function( request, response ) {
      $.getJSON( "ajax_functions.php", {
        term: extractLast( request.term ),
        console: $('select[name="console"] option:selected').val(),
        call: 'getCustomersEmailList',
        nmsAdmin: '<?php echo tep_session_id();?>',
        dataType:'json',
      },response ).fail(function(jqXHR, status, error){ document.location.href='login.php'; });
    },
    response: function(event, ui) {
        console.log(ui.content);
        if (ui.content.length === 0) {
            alert("No results found");
        }
    },
    change: function (event, ui) {
        if(!ui.item){
            $("#customers_name").val("");
        }
    },
    focus: function() {

      return false;
    },
    select: function( event, ui ) { 
      var customer_id = ui.item.customer_id;
      var customer_email = ui.item.customerEmail;
      console.log(ui);
      $('#customer_id').val(customer_id);
      $('#customer_email').val(customer_email);
      var terms = split( this.value );

      terms.pop();

      terms.push( ui.item.value );

      terms.push( "" );
      this.value = terms.join( "" );
      return false;
    },
    error : function() { document.location.href='login.php';}
});
Comments