There are several problems in the code for which you will get undefined
in variable mydata
:
The prueba
function does not return anything
You are assigning mydata
the value of the function prueba
... but test does not return anything, so mydata
will always be undefined
.
You want to perform a synchronous assignment of an asynchronous value
This is the real problem. The AJAX function is executed asynchronously (the call is made to the server and success / error is executed when the response returns) but the assignment is synchronous; therefore, even if prueba
returned a value, it would not work because that value would not have been assigned before returning it.
Possible solutions: you can change the function so that it returns a value and make the AJAX call synchronously (doing async:false
). This way you make sure that the value will be there when you return it. This option is not the best and it is not recommended .
Another better alternative would be to package the code that makes use of the variable mydata
in a function and call it in mycallback
(where the value of mydata
is assigned):
function prueba(callback){
$.ajax({
url: '/services/traps/view/',
type: "POST",
data: {
csrfmiddlewaretoken: csrftoken
},
success: callback ,
error: function(qXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(qXHR);
console.log(textStatus);
},
});
};
function mycallback(data){
//mi código
mydata = data;
operacionesConMyData();
};
function operacionesConMyData() {
// mover aqui las operaciones que necesiten mydata
}
// llamada al AJAX
prueba(mycallback);