Hendrik Eka Hendrik Eka - 5 months ago 27
Ajax Question

Ajax JSON response undefined in prompt field

I don't know what is wrong with my code. I tried to fill javascript prompt with ajax response. Here is my code :

$.ajax({
url: "{{ url('/dashboard/popfieldexist') }}",
dataType: "json",
type: 'POST',
data: "_token={{ csrf_token() }}&"+"selector="+f1[0].getAttribute('data-file'),
success: function (response) {
if(response){
getPopfield = response.data.field;
}else{
getPopfield = " ";
}
}
});
var title = prompt("File name : ", ""+getPopfield+"");


undefined

it display undefined..

Answer

An ajax call is usually asynchronous. So your prompt is called before the ajax finished.

Try:

   $.ajax({
        url: "{{ url('/dashboard/popfieldexist') }}",
        dataType: "json",
        type: 'POST',
        data: "_token={{ csrf_token() }}&"+"selector="+f1[0].getAttribute('data-file'),
        success: function (response) {
            if(response){
                getPopfield = response.data.field;
            }else{
                getPopfield = " ";
            }
            var title = prompt("File name : ", ""+getPopfield+"");
        }
    });