0

Here is my code:

function ajaxRequest(value, path, website){
    window[website] = $.ajax({
        url :  path,
        type : 'GET',
        data: { "name": value,
            "_token": $('meta[name="_token"]').attr('content')
        },

        beforeSend: function(){
            if(window[website] != null) {
                window[website].abort();
            }
        },
        success: function (people) {
            return [status, people];
        },

        error: function (jqXHR, textStatus, errorThrown) {
            return [status, textStatus];

        },

        timeout: 15000

    });

}

As you see, it's a function that sends ajax requests. I call it like this:

var res = ajaxRequest('Jack', 'search/twitter', 'twitter');
console.log(res);

It returns:

enter image description here

Why I don't see the result in the console? Noted that I can see the result in the console if I send that ajax out of function. (the result is an array of data)

How can I fix the problem?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • Are you using an async call to the ajax? if yes then the value may not be available to `res` when you are printing it in console where for regular async ajax call the success function is called when the async operation is completed. – Niladri Sep 23 '17 at 10:35

2 Answers2

1

For first you haven't return anything from your function, default is undefined.

Second, your res will not be the result of your ajax call. Because ajax is an asynchronous call, the result which will you get is accessible only in the function success or error.

See here. You can't return this. All other logic which you need to implement based on the data you need to write here.

success: function (people) {
     // Your logic here
},
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1
function ajaxRequest(value, path, website){

        return new Promise(function (resolve, reject) {
        window[website] = $.ajax({
            url :  path,
            type : 'GET',
            data: { "name": value,
                "_token": $('meta[name="_token"]').attr('content')
            },

            beforeSend: function(){
                if(window[website] != null) {
                    window[website].abort();
                }
            },
            success: function (people) {
                resolve([status, people]);
            },

            error: function (jqXHR, textStatus, errorThrown) {
                reject([status, textStatus]);

            },

            timeout: 15000

        });
    });
}

then do this, to get the result:

ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)})`;
3960278
  • 756
  • 4
  • 12
  • Seems nice, thank you, upvote. I will try it – Martin AJ Sep 23 '17 at 10:55
  • I don't know why always `reject()` executes. *(not `resolve()`)* – Martin AJ Sep 23 '17 at 11:35
  • That can only mean the Ajax call itself is failing, what is code you are getting in network trace? – 3960278 Sep 23 '17 at 11:37
  • Man, missed it, u r aborting the request before it is sent, it is always a reject. Why u need the before send block? – 3960278 Sep 23 '17 at 11:42
  • Ok, I fix the problem and it works as well now. Just I'm wondering, you have only 11 rep and lots of knowledge. how come? `:-)` – Martin AJ Sep 23 '17 at 11:45
  • :) people who r not there in SO does not mean they don’t know anything. – 3960278 Sep 23 '17 at 11:46
  • You are right ..! Also do you know how [this line](https://i.stack.imgur.com/uwuJr.png) prints in console? Is it printed automatically? Because I don't print it in my codes – Martin AJ Sep 23 '17 at 11:50
  • I think Juery logs it, sorry for the earlier comment u were actually logging return value which was undefined. – 3960278 Sep 23 '17 at 11:53
  • Yes seems Juery logs it. Just I don't understand, what you mean by *"sorry for the earlier comment u were actually logging return value which was undefined."* – Martin AJ Sep 23 '17 at 11:57
  • I edited the comment, which had some wrong information, thought u might have read it already. – 3960278 Sep 23 '17 at 11:58
  • Ah I see. And my last question: Why you have used two functions in `.then()`? Why not `.catch()`? – Martin AJ Sep 23 '17 at 12:00
  • .then is superset of .catch, which handles only the rejected case compared to .then which handled both. – 3960278 Sep 23 '17 at 12:03
  • So the second function into `.then()` is the same as `.catch()` ? – Martin AJ Sep 23 '17 at 12:05
  • In the pure JavaScript Promise, yes, people have different styles of writing, some will just miss the second argument of then and chain the output with .catch. I have to see if this is true for node’s bluebird – 3960278 Sep 23 '17 at 12:10