1

var data is my jquery variable, i want to add jsonData.image_name string text in to it. but keep saying 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;
}
vinayakj
  • 5,179
  • 3
  • 25
  • 45

1 Answers1

4

you cant return data from Asynchronous calls, you should do the manipulation in the success callback function. As callbacks are called when the data is arrived, but you are returning the data before that so you are getting 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)
vinayakj
  • 5,179
  • 3
  • 25
  • 45