-2

Is there a way to return the success data that is obtained by the AJAX call?

I am trying to do the following:

function myFunction(title) {
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: 'call_details_cache/',
        type: 'post',
        data: {
            phone: title,
            type_member: "cust",
            csrfmiddlewaretoken: csrftoken
        },
        success: function (data) {
        },
        failure: function (data) {
            alert('Got an error dude');
        }
    });
}

And then:

console.log(myFunction(title))

undefined is printed in my console. How can I fix it?

Thanks in advance!

Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
rishran
  • 596
  • 2
  • 7
  • 26

2 Answers2

1

Ajax is async, you are trying to access value like if it was sync. You need either a callback or a deferred...

Callback example:

function myFunction(title) {
            var csrftoken = getCookie('csrftoken');

                $.ajax({

                    url: 'call_details_cache/',
                    type: 'post',
                    data: {phone:title,   type_member: "cust", csrfmiddlewaretoken: csrftoken},
                    success: myFunctionCallback,

                    failure: function(data) { 
                        alert('Got an error dude');
                    }
                }); 
            }
function myFunctionCallback(data) {
     console.log(data);
}

Edit: This topic was already answered with a bunch of details. See How do I return the response from an asynchronous call?

Community
  • 1
  • 1
ben
  • 3,558
  • 1
  • 15
  • 28
0

You can use promise as following to achieve this:

function myFunction(title) {
    var csrftoken = getCookie('csrftoken');

    return $.ajax({

        url: 'call_details_cache/',
        type: 'post',
        data: {
            phone: title,
            type_member: "cust",
            csrfmiddlewaretoken: csrftoken
        }

    });
}

Then you can use it as:

var promise = myFunction(title);

promise.then(function (data) {
    console.log(data);
},
 function(reason) {
     alert('You got error dude');
});
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
Nikhil Batra
  • 3,118
  • 14
  • 19