-1

I have ajax function in custom function and I need to call my custom function and get some variable from the ajax function. Why this is not possible?

1st idea:

<script>
    function getValue(){

        $.nette.ajax({
            url: "http://example.com/request",
            contentType: 'application/json',
            dataType: 'json',
            success: function(payload) {
                console.log(payload.value); // contains RIGHT value
                return payload.value;
            }
        });
    }

    var try = getValue();
    console.log(try); // = undefined
</script>

2nd idea:

<script>
    function getValue(){
        var returning = "";

        $.nette.ajax({
            url: "http://example.com/request",
            contentType: 'application/json',
            dataType: 'json',
            success: function(payload) {
                returning = payload.value;
                console.log(payload.value); // contains RIGHT value
            }
        });
            console.log(returning); // = ""
    }

</script>
JackDavis
  • 117
  • 1
  • 4
  • 17

1 Answers1

2

ajax is a promise. use a callback to do something when the request was successful

function getValue(callback){
    $.nette.ajax({
        url: "http://example.com/request",
        contentType: 'application/json',
        dataType: 'json',
        success: function(payload) {
            callback(playload);
        }
    });
}
Mephiztopheles
  • 2,228
  • 1
  • 12
  • 25