Я упростил код, чтобы сосредоточиться на важной части и описать мою проблему.Последовательное выполнение с обещаниями и вызовом AJAX
У меня есть функция с запросом AJAX, возвращающим идентификатор.
function addProposal(){
var name_en = $("#name_en").val();
var use_en = $("#use_en").val();
var desc_en = $("#desc_en").val();
$.ajax({
type:'POST',
url:'http://localhost/index.php?option=com_test&task=addProposal&format=raw',
data:{ user_id: user_id,
name_en: name_en,
use_en: use_en,
desc_en: desc_en
},
beforeSend:function(){
$("#loading_modal").modal("show");
},
complete:function(){
$("#loading_modal").modal("hide");
},
done:function(id){
//------I get the ID here, when it's done----
alert(id);
idNewProposal=id;
}
});
}
Я называю эту функцию, когда пользователь нажимает на кнопку
$(document).ready(function()
{
//...
$(document).on('click', '#btn_add_valid', function() {
addProposal();
});
//...
}
Когда пользователь нажимает на эту кнопку, у меня есть еще одна функция, прикрепленную к событию, чтобы загружать файлы (см код ниже) , Моя проблема заключается в том, что мне нужно Ид сгенерированный в предыдущем вызове AJAX перед выполнением загрузки (строка «data.submit»)
$(document).ready(function()
{
//....
//Function to upload file
$('#file-upload').fileupload({
dataType: 'json',
autoUpload: false,
paramName: 'files[]',
maxNumberOfFiles:1,
add: function (e, data) {
//---The callback "add" is triggered each time that one file is selected
// I did not write all the code here but you have to know that I make some test
//for each selection under this callback (size and type of file).
//So if the user select a file which not match with the constraints,
//the input stay empty and an error message is displayed.
//--However I want to start the upload after the click on the button
$(document).on('click', '#btn_add_valid', function() {
data.formData = { id: idNewProposal}; //------I need the ID here----
data.submit(); //--The upload start Here (after the click on the button, all the files are sent)
});
},
done: function (e, data) {
$("#loading_file").modal("hide");
$("#validation_modal").modal("show");
},
progressall: function (e, data) {
var progress = parseInt(data.loaded/data.total * 100, 10);
$('#upload-file .bar').css(
'width',
progress + '%'
);
},
fail: function (e, data) {
alert('Error');
$("#loading_file").modal("hide");
}
});
}
Резюмируя: После нажатия на кнопку Мне нужно выполнить сначала addProposal(), и когда это будет сделано, мне нужно запустить загрузку (data.submit в $ ('# file-upload'). fileupload()) По-видимому, есть способ справиться с подобной проблемой с «обещаниями» в JQuery, но я не могу понять, как использовать его в этой ситуации.
Огромное спасибо любому, кто может помочь мне с этой проблемой.
Но ваша функция 'addProposal' делает ** не **' return' ничего? – Bergi
Вы правы, идентификатор не возвращается функцией, а по запросу Ajax idNewProposal = id; (когда запрос выполнен) – Lauradev
Что такое плагин 'fileupload', который вы используете? Когда/как часто он вызывает обратный вызов 'add', и что такое' data'? – Bergi