Search code examples
javascriptajaxreturn-value

AJAX function does not return any value


Problem

I have a JavaScript function which uses AJAX for getting a value from a MySQL table through PHP. I wrote all of my PHP and AJAX code correctly because when I check the result it receives, it shows the value as I want it to. So, the problem is when I receive the data correctly, I try to return it. But when I tried calling that function, even though it shows the correct value when I try seeing the value inside the AJAX function, as soon as I return it and check where I call the function, it shows "undefined".

Code Used

This is the AJAX function code -

function CheckUser(EmailID) {
     alert(EmailID);
     $.ajax("AJAXcommands\\CheckUser.php", {
          type: "POST", // type of the data we send (POST/GET)
          data: {
               EmailID: EmailID,
          },
          success: function (data) {
               // when successfully sent data and returned
               alert(data); //It returns correct value here
               return data;
          },
     });
}

And this is where I call the function -

function Confirm(button) {
     var input = document.getElementById("UserEmail");
     var checkUser = CheckUser(input.value);
     alert(checkUser); //This does not return correct value and return "undefined"
     if (input.value == "") {
          alert("Pls enter a value!");
     } else if (checkUser == "true") {
          alert("User Doesn't Exist!");
     } else {
          //Do Something...
     }
}

When I try alerting the data in the AJAX function it works correctly, but when I try alerting it in the second function, it returns "undefined"

Tried Solutions

I tried using the callback() method instead of return but it still does not work and returns the same result. I used callback() like this -

callback(data);

So does anyone has any solution to my problem? Thanks in advance!

By the way, thinking it is not relevant, I did not add PHP code, if I need to then please tell me in the comments.


Solution

  • function CheckUser(EmailID, callback) {
         alert(EmailID);
         $.ajax("AJAXcommands\\CheckUser.php", {
              type: "POST", // type of the data we send (POST/GET)
              data: {
                   EmailID: EmailID,
              },
              success: function (data) {
                   // when successfully sent data and returned
                   alert(data); //It returns correct value here
                   callback(data)
              },
         });
    }
    
    function Confirm(button) {
         var input = document.getElementById("UserEmail");
         CheckUser(input.value, data => {
              alert(data);
              if (input.value == "") {
                   alert("Pls enter a value!");
              } else if (data== "true") {
                   alert("User Doesn't Exist!");
              } else {
                   //Do Something...
              }
         }
    }