0

my custom javascript function is working fine. but the problem is it always returning false.

function uniqueChk()
{
    var flagV = false;
    jQuery.post("<?=base_url()?>index.php/authentication/chksid",
    { 
        sid: jQuery('#sid').val() 
    }, 
    function( data ) 
    {
        if(data == 'ok')
        {
            jQuery("#sid").removeClass("error");
            jQuery("#er_sid").html("");
            flagV = true;
        }
        else
        {
            jQuery("#sid").addClass("error");
            jQuery("#er_sid").html("This Student ID already in the database. Contact Admin if you have not done first time");
        }
    });
    return flagV;
}

If I got value of data "ok" its remove the class error from sid but still return false.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
reza
  • 1,507
  • 2
  • 12
  • 17

2 Answers2

1

try something like this

function uniqueChk()
{
    var flagV = false;
    $.ajax({
        type: 'POST',
        url: "<?=base_url()?>index.php/authentication/chksid",
        data: { sid: jQuery('#sid').val() },
        success: function(response){
          if(data == 'ok'){
                jQuery("#sid").removeClass("error");
                jQuery("#er_sid").html("");
                flagV = true;
          } else {
                jQuery("#sid").addClass("error");
                jQuery("#er_sid").html("This Student ID already in the database. Contact Admin if you have not done first time");
          }
        },
        async:false
    });
    return flagV;
}

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

That mean your function doesn't wait for your ajax response to complete.it return it value before your ajax request complete.so make ajax async

REFERENCE

http://api.jquery.com/jquery.ajax/

rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
0

Because your function returning before ajax gets a chance to come back. This is normal behavior for async functionality. Look into $.deferred when then.

Alex Shilman
  • 1,547
  • 1
  • 11
  • 15