Variable visibility in JavaScript?

  • 0
    Hello.
    There is a code:
    function isAdmin() {
    	var result = $.ajax({
    		url: '../php/index.php',
    		type: 'POST',
    		data: {'method': 'user.is_admin'},
    		success: function(data) {
    			if (data.response.code == 503) {
    				return false;
    			} else if (data.response.code == 504) {
    				return false;
    			}
    		}
    	});
    	return result;
    }

    I need the isAdmin () function itself to return true / false, but JS does not see the result variable, please help.
    jQuery Anonymous, Oct 17, 2019

  • 2 Answers
  • 0
    When the isAdmin function is called, an ajax request starts to be executed asynchronously in which the function is not blocked and the function returns from the function return result; .


    In your case, you can do a little differently. Use method done ()


    Example:
    function isAdmin () {
    var result = $.ajax({
    url: '../php/index.php',
    method: 'POST',
    data: { 'method': 'user.is_admin' },
    })

    return result
    }

    isAdmin().done(function (res) {
    if (res.status === "true") {
    // do something
    } else {
    // do something
    }
    })
    Vivien Fletcher

  • 0
    Read here: jquery.page2page.ru/index.php5/Ajax-%D0%B7%D0%B0%D ...

    and here is stackoverflow question. -from-inside ...

    Also specify the dataType: 'json' parameter. (This parameter indicates that you receive json in response)
    function isAdmin() {
    $.ajax({
    url: '../php/index.php',
    type: 'POST',
    data: {'method': 'user.is_admin'},
    dataType: 'json',
    success: handleResponse
    });
    }
    function handleResponse(result)
    {
    //здесь код для работы с результатом
    }



    You call isAdmin function - & gt; it receives the response and calls the handleResponse function with the result parameter.
    Conor Jacobs

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!