0

I'm making the following

function handler(data)
{
    return data;
}
function hit_db()
{
    $.ajax({
        url: target_url,
        type: 'GET',
        async: true,
        crossDomain: true,
        success: function (response){
            handler(response);
        }
    });
}
var status = hit_db();
return status;

However, if I try to alert(status) I get undefined

I know this is due to the async nature of ajax calls but I still can't seem to return response from the server successfully.

Curiously enough, If I write this

function handler(data)
{
    return data;
}
function hit_db()
{
    $.ajax({
        url: target_url,
        type: 'GET',
        async: true,
        crossDomain: true,
        success: function (response){
            alert(response);  // <---- Change is here
        }
    });
}
var status = hit_db();

I get it alerts the desired output success

Why is this happening? Isn't my callback function not setup properly? I have tried some online solutions but none seem to attempt to return a server response

net30
  • 197
  • 1
  • 11
  • `target_url` is a cross-domain but I'm using a CORS Toggle chrome extension to get around that issue purely for development purposes – net30 May 29 '18 at 06:18
  • May be its happens because your function nothing returning – Sachin Sarola May 29 '18 at 06:19
  • This post is not a directly answer to your question, but with it you can learn a bit about Ajax and responses: https://stackoverflow.com/questions/49614098/how-do-i-send-through-ajax-each-element-from-the-following-array/49617988#49617988 – Dani May 29 '18 at 06:20
  • I think it is returning something because else when I code `alert(response)` I would get `undefined` but I actually get the desired output @SachinSarola – net30 May 29 '18 at 06:22
  • Yes you are right its because of the async nature - The way you have implemented the code you require synchronous call. You will get the correct data in handler function. But as the statement var status = hit_db(); is already calls and async function you will not get the correct value there – patilprashant6792 May 29 '18 at 07:10
  • @net30 if you want to something in status variable than you should return something from hit_db() function and your ajax response scope end after success block that's why I told returning nothing – Sachin Sarola May 29 '18 at 07:28

0 Answers0