Can't parse and return ajax string to jquery variable
var data
is my jquery variable, i want to add jsonData.image_name
string text to it . but keep talking undefined
when it passes.
function SaveAndGetImageName() {
var data = "";
var formData = new FormData();
formData.append('btn_Browse', $('#btn_Browse')[0].files[0]);
$.ajax({
url: '../Gem/SaveProfilePic',
type: 'POST',
dataType: 'json',
cache: false,
async: true,
contentType: false,
processData: false,
data: formData,
success: function (jsonData) {
data = jsonData.image_name;
}
});
return data;
}
+1
source to share
1 answer
you cannot return data from asynchronous calls, you must do the manipulation in the success callback function. When called calls are called when data arrives but you are returning data before to get it undefined
.
function SaveAndGetImageName(processImageNameCallback) {
var data = "";
var formData = new FormData();
formData.append('btn_Browse', $('#btn_Browse')[0].files[0]);
$.ajax({
url: '../Gem/SaveProfilePic',
type: 'POST',
dataType: 'json',
cache: false,
async: true,
contentType: false,
processData: false,
data: formData,
success: function (jsonData) {
data = jsonData.image_name;
processImageNameCallback(data);
}
});
return data;
}
function processImageName(imageName){
// do stuff with image name
alert(imageName);
}
SaveAndGetImageName(processImageName)
+3
source to share