Javascript not working with php

I am using a PHP script that returns "y" or "n" depending on user input, which is passed through the variables uname

and pass

. I am using ajax method $.get()

to call PHP script.

If I try to output the data in the method $.get()

, it works fine, but gives a problem when I use an if statement to compare a value with "y" or "n".

My code looks like this:

    var status;
    $('#login').click(function(){
    $.get("login.php", { uname: document.getElementById('uname').value, pass: document.getElementById('pass').value } )
    .done(function( data ) {
        status=data;
        alert(status);  //This works
    });

    if(status=='y')
    {
        alert('yes!');    //This is not working
        // window.location.replace("welcome.html");
    }
    else if(status=='n')
    {
        alert('no!');     //This is not working
    }
});

      

Any help would be greatly appreciated.

+3


source to share


3 answers


Move the condition if

inside ajax due to the asynchronous nature of ajax:



var status;
  $('#login').click(function(){
  $.get("login.php", { uname: document.getElementById('uname').value, pass: document.getElementById('pass').value } )
  .done(function( data ) {
      status=data;

        if(status=='y')
        {
          alert('yes!');
        }
        else if(status=='n')
        {
          alert('no!');
        }      
  });
});

      

+5


source


This is a typical async problem. You make a query, compare a result that has not yet returned with some rows, then the answer comes to your query - too late is important for it. Too fast with your checkout. Place state comparisons inside a callback done

.



+3


source


since ajax is asynchronous by the time the code enters the conditional statuses, the request code may not be returned , so the var status may not have been initialized yet . Try to put conditional statuses inside the executed function, for example:

$('#login').click(function(){
$.get("login.php", { uname: document.getElementById('uname').value, pass:       document.getElementById('pass').value } )
.done(function( data ) {
    if(data =='y')
    {
        alert('yes!');
       // window.location.replace("welcome.html");
    }
    else if(data =='n')
    {
        alert('no!');
    }
});

      

I think this should do the trick;) ... for further clarification you can visit the jQuery ajax api documentation: http://api.jquery.com/jquery.ajax/

+1


source







All Articles