Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not working with php

I am using a PHP script that returns 'y' or 'n' depending on the data entered by the user, which is being passed through the variables uname and pass. I am using the ajax $.get() method to call the php script.

If I try to output the data within the $.get() method, it works perfectly but gives a problem when I use an if statement to compare the value with 'y' or 'n'.

My code goes 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.

like image 702
Pranav Avatar asked Dec 05 '25 13:12

Pranav


2 Answers

Move your if condition inside ajax due to async 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!');
        }      
  });
});
like image 54
Dev01 Avatar answered Dec 07 '25 03:12

Dev01


This is a typical async problem. You make a request, compare the result that didn't come back yet with some strings, then the response to your request comes - way too late for it to matter. You are too fast with your check. Put your status comparisons inside the done callback.

like image 29
Amadan Avatar answered Dec 07 '25 02:12

Amadan