Search code examples
javascriptjqueryajaxasynchronousjquery-callback

jQuery can't alert anything or redirect inside an plugin's callback function


I use a plugin to upload images which is working fine, the code is:

$('input[name=photo]').change(function(e) {
    var file = e.target.files[0];

    $.canvasResize(file, {
        width: 600,
        height: 500,
        crop: false,
        quality: 90,
        callback: function(data, width, height) {

            if(width > 100)
            {

            }
            else
            {
                alert("this is not an image"); // this isn't working
                return false;
            }

            var fd = new FormData();
            var f = $.canvasResize('dataURLtoBlob', data);
            f.name = file.name;
            fd.append($('input[name=photo]').attr('name'), f);

            $.ajax({
                url: 'doupload.php',
                type: 'POST',
                data: fd,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function() {
                    window.location.href = "http://www.stackoverflow.com"; // THIS ISN'T WORKING TOO
                }
            })
        }
    });
});

Now after it's done I try to redirect to another page after AJAX is finished but it's not working, alerts are also not working. Any ideas?


Solution

  • $.ajax({
                    url: 'doupload.php',
                    type: 'POST',
                    data: fd,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function() {
                        location.href = "http://www.stackoverflow.com";
                    },
                    error: function() {
                        //handle errors here
                    },
                    complete: function() {
                        // this code is always executed
                        location.href = "http://www.stackoverflow.com";
                    }
    })
    

    Or

    var jqXHR = $.ajax({...
                });
    jqXHR.always(function(){
          location.href = "http://www.stackoverflow.com";
    })