-5

Below function always alerts undefined. Code execution is completed before the ajax request is completed. Kindly help .

function validateUser() {
    var user = document.getElementById("user").value
    var isuserValid = isvalidUser(user);
    alert("returned Result:" + isuserValid); // it always prints undefined,ajax request not completed.How can i wait for ajax request to complete 
    if (isuserValid) {
        alert("user Account found);
        } else {
            alert("Invalid user");
        }
    }

    function isValidUser(user) {
        $.ajax({
            url: 'validateUser.jsp'
            type: 'GET',
            dataType: 'html'
            data: {
                userName: user
            },
            success: function(data) {
                if (data.trim() = "true")
                    return true;
            } else {
                return false;
            }
        });
    }

//it always alerting undefined 
Shambhavi
  • 305
  • 1
  • 14

2 Answers2

0

Put the alert in the success callback of the AJAX request. This will only run the alert after the AJAX request has completed.

Huan Zhang
  • 1,095
  • 8
  • 13
  • 1
    I'll expect that this question will be closed soon. Its a duplicate. But you have an answer that points to the solution. Expand it so the OP learns more about asynchronous coding and you'll score points – Mouser Aug 07 '15 at 09:31
  • I used ajax inside the method. Method call returned before completing ajax call. So how can i wait for ajax call completion. – Arun Kumar Tirunelveli Aug 07 '15 at 09:33
  • I hate giving people exact solutions to their problems though, they won't even think about the problem and will never learn. I like to point them in the right direction and let them find the solution themselves :) – Huan Zhang Aug 07 '15 at 09:33
  • you see that inside your AJAX call you are running an anonymous function with the argument (data). Try alert(data) inside that function and you should see some results :) – Huan Zhang Aug 07 '15 at 09:35
0

If you want synchronous AJAX, you need to set async: false in your request; which is true by default.

function isValidUser(user) {
        $.ajax({
            url: 'validateUser.jsp'
            type: 'GET',
            async: false,
            dataType: 'html'
            data: {
                userName: user
            },
            success: function(data) {
                if (data.trim() = "true")
                    return true;
            } else {
                return false;
            }
        });
    }

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Shambhavi
  • 305
  • 1
  • 14