I'm trying to get the data out of the success part of an AJAX call. So I tried to write a callback function for that purpose. I have this code :
var data2;
$(function () {
function callback(data) {
console.log(data);
data2 = JSON.parse(data);
console.log(data2);
}
$("myForm")
.submit(function (event) {
$.ajax({
type: 'POST',
url: "/...",
data: "JASON",
success: callback
});
});
console.log(data2);
});
In the console I see this in that order :
undefined
, content of data
and content of data2
.
What I can't understand is, why am I getting undefined
at first? Shouldn't I be geting the value of data
first? Why is the last console.log is executed first? And most importantly, is my approach to get data from AJAX call is correct? What else can I do to get data? Thanks.