0

I have tried with this code. But it is not working. I just need to return state of bool value. But always this returns true.

function nic_is_exist(){

  var state = true;
  var nic = document.getElementById("tbNic").value;
  var xmlhttp;
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  } 
  xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState == 1){
      document.getElementById("spNic").innerHTML="<img src='../Style/images/loarding.gif' />";  
    }     
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("spNic").innerHTML="";
      var str = xmlhttp.responseText;
      alert(str+2);
      if( str != "1"){
        alert("if");
        fill_form(str);
        checkNull();
        state = true;   
      }else{
        alert("else");
        state = false;
      }       
    }     
  }
  xmlhttp.open("POST","rpoRegister_PHP.php?a="+nic,true);
  xmlhttp.send();
  return state;
}
dee-see
  • 23,668
  • 5
  • 58
  • 91
Harshana
  • 185
  • 3
  • 4
  • 12

3 Answers3

0

your ajax request run Asynchronous so before your ajax request complete your function return your state variable value which is true during initialize

You should move whatever you need to do with that return value into the function itself.

There are basically two ways how to solve this:

  1. Make the AJAX call synchronous (lets call it SJAX).

  2. Restructure your code to work properly with callbacks.

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

AJAX is asynchronous. If you need to do something based on the TRUE/FALSE then you need to put it within your if (xmlhttp.readyState==4 && xmlhttp.status==200) block. Or replace your state = true; and state = false; code with a function call.

Example:

if( str != "1"){
    alert("if");
    fill_form(str);
    checkNull();
    doSuccessCode(); 
  }else{
    alert("else");
    doFailCode();
  }
gfrobenius
  • 3,987
  • 8
  • 34
  • 66
  • `function setState(s){ ajaxState = s; //ajaxState is a globle veriable alert("setState -> "+ajaxState); }` but not working – Harshana Jan 09 '14 at 07:17
0

depends on how you echo responseText from rpoRegister_PHP.php have you try to use .trim() before you compare them? It might be an extra space.

  var str = xmlhttp.responseText.trim();
  alert(str+2);
  if( str != "1"){
    alert("if");
    fill_form(str);
    checkNull();
    state = true;   
  }else{
    alert("else");
    state = false;
  }