I have simplified the code just to focus on the essential part and to describe my problem.
I have a function with an AJAX request returning an ID.
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;
}
});
}
I call this function when the user click on a button
$(document).ready(function()
{
//...
$(document).on('click', '#btn_add_valid', function() {
addProposal();
});
//...
}
When the user click on this button I have another function attached to the event in order to upload files (see code below). My problem is that I need the Id generated in the previous AJAX call before executing the upload (line "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");
}
});
}
To summarize: After a click on the button I need to execute first the addProposal() function and when it's done, I need to launch the upload (data.submit in $('#file-upload').fileupload()) Apparently there is a way to manage this kind of problem with "promises" in Jquery but I can't understand how to use it in this situation.
A huge thanks to anybody able to help me with this problem.