Upload a file with jQuery without opening a new page

ajax-with-jquery

In this example we are going to upload a file to our url using AJAX with jQuery.

// We need to select the file in our form before pressing submit   
$("#form-import")
    .submit(function(e) {
        $.ajax({
            url: "/upload/file.txt",
            type: "POST",
            data: new FormData(this),
            processData: false,
            contentType: false
        }).done(function() {
            dialogmessage.show($._("File uploaded"));
        }).fail(function() {
            dialogmessage.show($._("Fail uplading the file"));
        });
        e.preventDefault(); // Avoid launch new page
    });

Here if you want you can download my AJAX logo and use it for free: AJAX logo