-3

I am looking to store a value which is return by the AJAX function, here is the my code, in the AJAX success it is showing well, but when am storing that data which is saying undefined.

The following serviceNumber, which I am storing the enCrypt return value

var serviceNumber = enCrypt(typeofServiceNumber);// when am catching the function data which is saying "undefined"

the following code is my ajax function

function enCrypt(id) {
if (id > 0) {
    $.ajax({
        url: $("baseUrl").html() + "JobProfiles/Encryption",
        type: "POST",
        dataType: "json",
        data: { Id: id },
        success: function (encdata) {
                   return encdata; 
        },
        error: function (data) {
            $('#loading').hide();
        }
    });
}
}

Can you help me to know what is wrong in my code? Thanks in advance.

Maak
  • 4,720
  • 3
  • 28
  • 39
  • 2
    Possible duplicate of [access to a variable "outside" of a callback function in javascript](https://stackoverflow.com/questions/42666843/access-to-a-variable-outside-of-a-callback-function-in-javascript) – raul.vila Apr 16 '18 at 11:02
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Durga Apr 16 '18 at 11:03

2 Answers2

0

You can't use return like this, because the function is async + it's a function in a function...so actually yeah you cant return there xD

Just do something like:

enCrypt(typeofServiceNumber);

//and in your ajax:
success: function (encdata) {
                   go_on(encdata);
        },

//and then
function go_on(serviceNumber)
{
    //here you can use it :D
}
0

just add the

 cache: false,
 async: false,

to you ajax function

function enCrypt(id) {
var encnum;
$.ajax({
    url: $("baseUrl").html() + "JobProfiles/EncodeIds",
    type: "POST",
    cache: false,
    async: false,
    dataType: "Json",
    data: { Ids: id },
    success: function (encdata) {
        encnum = encdata;
    },
    error: function (data) {
        $('#loading').hide();
    }

    });
    return encnum;

}