0

I am trying to get my jQuery synchronous ajax call to return a boolean value, but all I get when I test the return value is 'undefined'.

jQuery code:

function foo() {
    var username = "hello"
    if (checkUsernameExist(username)) {
        //do something here
    }
}

function checkUsernameExist(username) {
    return $.ajax({
        type: 'POST',
        url: "check_username.php",
        data: { username: username},
        async: false,
    }).responeText;
}

PHP code:

<?php
    //sets up connection (among other things)
include 'common.php';

//check we have username post var
if(isset($_POST['username']))
{
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    }

    $un = $_POST['username'];

    //check username in db
    $results = pg_query($con,"SELECT * FROM users WHERE username='{$un}'");

    //return total count
    $username_exist = pg_num_rows($results); //total records

    if ($username_exist == 1) {
        echo true;
    } else {
        echo false;
    }
}
?>

Thanks in advance.

Josh Noe
  • 2,664
  • 2
  • 35
  • 37
sooty1892
  • 327
  • 1
  • 3
  • 13
  • @JoshNoe That is not a duplicate. – Kevin B May 29 '14 at 19:10
  • @KevinB how is it not? It's the typical "misunderstanding of AJAX" question that's asked dozens of times a day. He's trying to get a return value from an AJAX call instead of using a callback. – Josh Noe May 29 '14 at 19:20
  • 1
    The typical mis-understanding involves asynchronous requests where it isn't possible to return. In this case he's using synchronous, making it possible to return the value. – Kevin B May 29 '14 at 19:21
  • @KevinB Point taken, although I doubt synchronous AJAX is really what the OP needs. If so, synchronous AJAX should be explicitly mentioned in the question. It's a very uncommonly needed, but often misguidedly-used, option with AJAX. Submitted an edit. – Josh Noe May 29 '14 at 19:42

2 Answers2

3

i mostly use success call back and it works:

function checkUsernameExist(username) {
     var Exists;
     $.ajax({
        type: 'POST',
        url: "check_username.php",
        data: { username: username},
        async: false,
        success: function(response){

        Exists =  response;
        }
    })
  reutrn Exists;
}

Note:

It's not a recommended practice to make Ajax calls synchronous as they will halt the UI on the browser. If the Ajax call takes too long to complete, the user won't be able to do anything on the website until it's done.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

The jQuery ajax() function returns a promise object. Since Ajax calls are asynchronous, you need a way to ensure that they will always complete, successfully or not. A promise object can let you write logic for:

  • A succesfully completed call via the .done() function.
  • Checking whether an error occurred on the server side, via the .fail() function.
  • Run code regardless of status via the .always() function.
  • Chain Ajax calls (i.e. .when() and .then()). This is one I haven't personally worked with, however.

The following will work for you:

JS:

function foo() {
    var username = "hello"
    checkUsernameExist(username, function (status) {
        // Do something here
    });
}

function checkUsernameExist(username, callback) {
    $.ajax({
        type: 'POST',
        url: "check_username.php",
        data: { username: username},
        async: true
    }).done(function (data) {
        callback(data.result === true);
    }).fail(function (jqXhr, textStatus, errorThrown) {
        callback(false);
    });
}

PHP (forgive me since I'm not familiar with PHP. The point is to return JSON.

if ($username_exist == 1) {
    echo '{"result": true}';
} else {
    echo '{"result": false}';
}

You can read more about Deferreds here:

Mario J Vargas
  • 1,185
  • 6
  • 12
  • It doesn't make much sense returning JSON for just a true/false result. – JJJ May 29 '14 at 18:14
  • I agree, but I didn't want him doing string comparisons `"true" === data`... I think the point at hand is whether my answer addresses his problem. That's a decision that he can make himself. – Mario J Vargas May 29 '14 at 18:15
  • What's wrong with string comparisons? – JJJ May 29 '14 at 18:17
  • Nothing wrong with it. I did agree with you previously. It's one solution to a problem. Whether he returns a "true" or "false" string or JSON is irrelevant as it is a design decision. – Mario J Vargas May 29 '14 at 18:23
  • what this means:``callback(data.result === true);`` in done – Ehsan Sajjad May 29 '14 at 18:24
  • Nothing wrong with it, you just didn't want him do it... never mind. – JJJ May 29 '14 at 18:26
  • @EhsanSajjad : It's simply passing a `true` or `false` value to the callback function introduced by the anonymous function in `foo()`. I could have written it this way: `var userExists = (data.result === true); callback(userExists);` – Mario J Vargas May 29 '14 at 18:27