C
C
Cyril2017-04-20 21:34:11
JavaScript
Cyril, 2017-04-20 21:34:11

Ajax inside a function, how to return request result?

Authorization itself in JS , there is a common request function and authorization check

function getAjax(url,data,callback) {
    var patch = 'http://server.ser/mobile_app/';
    $.ajax({
        url:patch + url,
        type:'POST',
        dataType:'json',
        data:data,
        success:callback,
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('Ошибка: ' + textStatus + ' | ' + errorThrown);
        }
    });
}

function try_login (login,pass) {
    var ret = false;
    getAjax('try_login.php',{login:login,pass:pass},function(data){
        if (typeof data.success != 'undefined' && data.success == 'ok') {
            ret = true;
            console.log('try login true');
            ret = true;
        }
    });
    return ret;
}


Naturally, try_login returns false, because asynchrony, but async:false doesn't suit me, because the function will run continuously. In theory, I understand how to do it right in my case, it's something like:
//хотел так
    if (try_login('login','pass')) {
        alert('Ура');
    }

    // а придется как-то так
    getAjax('try_login.php',{login:'login',pass:'pass'},function(data){
        if (typeof data.success != 'undefined' && data.success == 'ok') {
            alert('Не очень ура');
        }
    });


The first option is just more minimalistic and beautiful to the eye, maybe someone knows a way not to leave it???

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pushkarev, 2017-04-20
@AXP-dev

Here it is https://developer.mozilla.org/ru/docs/Web/JavaScri...

F
Faliah, 2017-04-21
@Faliah

One option is to use deferred which comes out of the box:

function getEndpoint(method, url) {
  var apiBaseUrl = 'http://server.ser/mobile_app/'
  
  return function(data) {	
    
    return $.ajax({
      url: apiBaseUrl + url,
      type: method,
      dataType: 'json',
      data: data
    })
  }
}

var tryLogin = getEndpoint('POST', '/post');

tryLogin({ user: 'Foo', pass: 'bar' })
  .done(function(data) { 
    if (typeof data.success != 'undefined' && data.success == 'ok') {
      console.log('try login true');    
    }
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    console.log('Ошибка: ' + textStatus + ' | ' + errorThrown);
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question