javascript - event.returnValue is deprecated. Please use the standard event.preventDefault() instead

19
2014-04
  • Alex Parakhnevich

    I have this script:

    <script>
    $(document).ready(function () {
        $("#changeResumeStatus").click(function () {
            $.get("{% url 'main:changeResumeStatus' %}", function (data) {
                if (data['message'] == 'hidden') {
                    $("#resumeStatus").text("скрыто");
                } else {
                    $("#resumeStatus").text("опубликовано");
                }
            }, "json");
        });
    });
    </script>
    

    I receive the following error in my Google Chrome console:

    event.returnValue is deprecated. Please use the standard event.preventDefault() instead.

    I am using jQuery v1.10.2 and #changeResumeStatus is a <span>.

    What's wrong with my script?

  • Answers
  • Paul Mougel

    This is only a warning: your code still works, but probably won't work in the future as the method is deprecated. See the relevant source of Chromium and corresponding patch.

    This has already been recognised and fixed in jQuery 1.11 (see here and here).

  • Peter Mortensen

    That's your jQuery API problem, not your script. There is not much to worry about.

  • ensignr

    If you using Bootstrap:

    The current version of Bootstrap (3.0.2) (with jQuery 1.10.2 & Chrome) seems to generate this warning as well.

    (It does so on Twitter too, BTW.)

    Update

    The current version of Bootstrap (3.1.0) no longer seems to generate this warning.

  • Ledivin

    Just for other's reference, I just received this and found it was due to AngularJS. It's for backwards compatibility:

    if (!event.preventDefault) {
        event.preventDefault = function() {
            event.returnValue = false; //ie
        };
    }
    
  • numediaweb

    This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/

    One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..

    It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)

  • Nick Rippe

    I found that using the latest version will fix this problem:
    http://code.jquery.com/jquery-git.js


  • Related Question

    ajax - How can I upload files asynchronously with jQuery?
  • Sergio del Amo

    I would like to upload a file asynchronously with jQuery. This is my HTML:

    <span>File</span>
    <input type="file" id="file" name="file" size="10"/>
    <input id="uploadbutton" type="button" value="Upload"/>
    

    And here my JavaScript code:

    $(document).ready(function () {
        $("#uploadbutton").click(function () {
            var filename = $("#file").val();
    
            $.ajax({
                type: "POST",
                url: "addFile.do",
                enctype: 'multipart/form-data',
                data: {
                    file: filename
                },
                success: function () {
                    alert("Data Uploaded: ");
                }
            });
        });
    });
    

    Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?

    Current Solution

    I am using the jQuery Form Plugin to upload files.


  • Related Answers
  • Afzaal Ahmad Zeeshan

    With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

    The HTML:

    <form enctype="multipart/form-data">
        <input name="file" type="file" />
        <input type="button" value="Upload" />
    </form>
    <progress></progress>
    

    First, you can do some validation if you want. For example, in the onChange event of the file:

    $(':file').change(function(){
        var file = this.files[0];
        var name = file.name;
        var size = file.size;
        var type = file.type;
        //Your validation
    });
    

    Now the Ajax submit with the button's click:

    $(':button').click(function(){
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: 'upload.php',  //Server script to process data
            type: 'POST',
            xhr: function() {  // Custom XMLHttpRequest
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // Check if upload property exists
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                }
                return myXhr;
            },
            //Ajax events
            beforeSend: beforeSendHandler,
            success: completeHandler,
            error: errorHandler,
            // Form data
            data: formData,
            //Options to tell jQuery not to process data or worry about content-type.
            cache: false,
            contentType: false,
            processData: false
        });
    });
    

    Now if you want to handle the progress.

    function progressHandlingFunction(e){
        if(e.lengthComputable){
            $('progress').attr({value:e.loaded,max:e.total});
        }
    }
    

    As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.

  • giorgio

    There are various ready-made plugins on doing file upload on jQuery.

    Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.

    Here's few:

    You can search more from jQuery's plugin site.

  • Peter Mortensen

    You cannot do Ajax file uploads. They're not supported, but you can fake it.

    If you create an iframe on the page (that you can hide with CSS), you can target your form to post to that iframe.

    Because it's a real post, it's not wholly interactive so you'd need to look at requesting the progress of the current upload from your server. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.

    If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.

    Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...

  • user12287

    I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:

    $(document).ready(function() {
        $("#uploadbutton").jsupload({
            action: "addFile.do",
            onComplete: function(response){
                alert( "server response: " + response);
            }
        });
    
  • Jordan Feldstein

    This AJAX file upload jQuery plugin uploads the file somehwere, and passes the response to a callback, nothing else.

    • It does not depend on specific HTML, just give it a <input type="file">
    • It does not require your server to respond in any particular way
    • It does not matter how many files you use, or where they are on the page

    -- Use as little as --

    $('#one-specific-file').ajaxfileupload({
      'action': '/upload.php'
    });
    

    -- or as much as --

    $('input[type="file"]').ajaxfileupload({
      'action': '/upload.php',
      'params': {
        'extra': 'info'
      },
      'onComplete': function(response) {
        console.log('custom handler for file:');
        alert(JSON.stringify(response));
      },
      'onStart': function() {
        if(weWantedTo) return false; // cancels upload
      },
      'onCancel': function() {
        console.log('no file selected');
      }
    });
    
  • Peter Mortensen

    You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. Try the SWF (Flash) uploader SWFUpload.

    Or the excellent jQuery Form Plugin that posts your files through an iframe to get the effect.

  • Peter Mortensen

    I just found this awesome tool to do asynchronous file uploading. It is written in jQuery and you can interact with it through jQuery. Check out Plupload.

    It uses these different "runtimes", ranging from HTML 5/4 to Flash to Gears. Here's an example of all the runtimes in one page...

    http://www.plupload.com/example_all_runtimes.php

    I highly recommend Plupload; it's awesome!

  • Peter Mortensen

    I have been using the below script to upload images which happens to work fine.

    HTML

    <input id="file" type="file" name="file"/>
    <div id="response"></div>
    

    JavaScript

    jQuery('document').ready(function(){
        var input = document.getElementById("file");
        var formdata = false;
        if (window.FormData) {
            formdata = new FormData();
        }
        input.addEventListener("change", function (evt) {
            var i = 0, len = this.files.length, img, reader, file;
    
            for ( ; i < len; i++ ) {
                file = this.files[i];
    
                if (!!file.type.match(/image.*/)) {
                    if ( window.FileReader ) {
                        reader = new FileReader();
                        reader.onloadend = function (e) {
                            //showUploadedItem(e.target.result, file.fileName);
                        };
                        reader.readAsDataURL(file);
                    }
    
                    if (formdata) {
                        formdata.append("image", file);
                        formdata.append("extra",'extra-data');
                    }
    
                    if (formdata) {
                        jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
    
                        jQuery.ajax({
                            url: "upload.php",
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function (res) {
                             jQuery('div#response').html("Successfully uploaded");
                            }
                        });
                    }
                }
                else
                {
                    alert('Not a vaild image!');
                }
            }
    
        }, false);
    });
    

    Explanation

    I use response div to show the uploading animation and response after upload is done.

    Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data as in the script.

    At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST data.

    Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.

  • random

    I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.

    The challenge is in getting AJAX upload working as the standard remote_form_for doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.

    That's where the jQuery-form plugin comes into play.

    Here’s the Rails code for it:

    <% remote_form_for(:image_form, 
                       :url => { :controller => "blogs", :action => :create_asset }, 
                       :html => { :method => :post, 
                                  :id => 'uploadForm', :multipart => true }) 
                                                                            do |f| %>
     Upload a file: <%= f.file_field :uploaded_data %>
    <% end %>
    

    Here’s the associated JavaScript:

    $('#uploadForm input').change(function(){
     $(this).parent().ajaxSubmit({
      beforeSubmit: function(a,f,o) {
       o.dataType = 'json';
      },
      complete: function(XMLHttpRequest, textStatus) {
       // XMLHttpRequest.responseText will contain the URL of the uploaded image.
       // Put it in an image element you create, or do with it what you will.
       // For example, if you have an image elemtn with id "my_image", then
       //  $('#my_image').attr('src', XMLHttpRequest.responseText);
       // Will set that image tag to display the uploaded image.
      },
     });
    });
    

    And here’s the Rails controller action, pretty vanilla:

     @image = Image.new(params[:image_form])
     @image.save
     render :text => @image.public_filename
    

    I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.

  • Darryl Hein

    A solution I found was to have the <form> target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).

  • Peter Mortensen

    You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:

    var xhr = new XMLHttpRequest();
    xhr.upload.onprogress = function(e) {
        var percent = (e.position/ e.totalSize);
        // Render a pretty progress bar
    };
    xhr.onreadystatechange = function(e) {
        if(this.readyState === 4) {
            // Handle file upload complete
        }
    };
    xhr.open('POST', '/upload', true);
    xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
    xhr.send(file);
    
  • ivan_pozdeev

    jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.

    $('#file_upload').uploadify({
        'swf': '/public/js/uploadify.swf',
        'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
        'cancelImg': '/public/images/uploadify-cancel.png',
        'multi': true,
        'onQueueComplete': function (queueData) {
            // ...
        },
        'onUploadStart': function (file) {
            // ...
        }
    });
    

    I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:

    $(document).ready(function () {
        $('#btn_Upload').live('click', AjaxFileUpload);
    });
    
    function AjaxFileUpload() {
        var fileInput = document.getElementById("#Uploader");
        var file = fileInput.files[0];
        var fd = new FormData();
        fd.append("files", file);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", 'Uploader.ashx');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                 alert('success');
            }
            else if (uploadResult == 'success')
                alert('error');
        };
        xhr.send(fd);
    }
    
  • user1091949

    Simple Ajax Uploader is another option:

    https://github.com/LPology/Simple-Ajax-Uploader

    • Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
    • Supports multiple, concurrent uploads -- even in non-HTML5 browsers
    • No flash or external CSS -- just one 5Kb Javascript file
    • Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
    • Flexible and highly customizable -- use any element as upload button, style your own progress indicators
    • No forms required, just provide an element that will serve as upload button
    • MIT license -- free to use in commercial project

    Example usage:

    var uploader = new ss.SimpleUpload({
        button: $('#uploadBtn'), // upload button
        url: '/uploadhandler', // URL of server-side upload handler
        name: 'userfile', // parameter name of the uploaded file
        onSubmit: function() {
            this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
        },
        onComplete: function(file, response) {
            // do whatever after upload is finished
        }
    });