I have this code:
function subirArchivos()
{
var archivos = null;
var imagen = $("#uploadImage")[0];
var video = $("#uploadVideo")[0];
var formData = new FormData();
formData.append("uploadArchivos[0]", imagen.files[0]);
formData.append("uploadArchivos[1]", video.files[0]);
$.ajax({
url: 'uploadArchivos.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
xhr: function () {
xhr = $.ajaxSettings.xhr();
$("#cargar").show();
$("#cargar .progress-bar").attr("aria-valuenow", 0);
$("#cargar .progress-bar").css("width", "0%");
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable)
{
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
$("#cargar .progress-bar").attr("aria-valuenow", percentComplete);
$("#cargar .progress-bar").css("width", percentComplete + "%");
if(percentComplete == 100)
{
setTimeout(function(){
$("#cargar").hide();
}, 2000);
}
}
}
return xhr;
},
success: function(data){
if(data != "error")
archivos = jQuery.parseJSON(data);
else
$("#error-subir").show();
}
});
return archivos;
}
subirArchivos()
As you can see, the function is in charge of uploading files to the server by means of an ajax request, now when I receive a response from the server in the function that is called in the success, if the response is different from an error, what I do is parse the JSON that It is being received and later I save it in the variable archivos
since this is the one that I want the function to return as a value subirArchivos()
.
function insertarPelicula()
{
var formulario = $("#form-registro");
var titulo = $("#tituloVal").val();
var clasificacion = $("#clasificacionVal").val();
var genero = $("#generoVal").val();
var duracion = $("#duracionVal").val();
var pais = $("#paisVal").val();
var ano = $("#anoVal").val();
var sinopsis = $("#sinopsisVal").val();
var actores = $("#actoresVal").val();
var directores = $("#directoresVal").val();
if(formulario.valid())
{
var archivos = subirArchivos();
if(archivos == null)
return false;
$.ajax({
url: "insert.php",
data: "titulo=" + titulo + "&clasificacion=" + clasificacion + "&genero=" + genero + "&duracion=" + duracion
+ "&pais=" + pais + "&ano=" + ano + "&sinopsis=" + sinopsis + "&actores=" + actores
+ "&directores=" + directores + "&archivos=" + JSON.stringify(archivos),
type: "POST",
success: function(data){
if(data == 1)
{
$("#correcto").fadeIn(3000);
setTimeout(function(){
window.location.reload(true);
}, 2000);
}
else
$("#error").fadeIn(3000);
}
});
}
}
The function insertarPelicula()
is the one that calls the function subirArchivos()
that returns a value. The problem here is that I can't get the function subirArchivos()
to return the JSON that is obtained when uploading the files, it returns pure null.
Your problem is a classic one: expect synchronous behavior from asynchronous code .
We are going to divide your function into
subirArchivos( )
2 parts: what is executed synchronously (from beginning to end), and what is asynchronous.Even though it looks like it doesn't, your code executes exactly as I've shown . All synchronous code runs from start to finish . The asynchronous part is waiting to be executed: in your case, waiting for the AJAX response.
Your problem is clearly visible: your variable
archivos
is returned with the last assigned value... in your case,null
.The solution is the usual one in these cases: do not wait for a return value from an asynchronous code, but call from the asynchronous code what requires said value: