Search code examples
jqueryblueimp

$('#fileupload').fileupload function is not calling


I am configuring blueimp to upload image on click to post button. My problem is it is not calling the $('#fileupload').fileupload function. I have included following javascript files. The following is my code please see what is the problem.

<head>
    <script  type="text/javascript" src="../../js/jquery.min.js"></script>
    <script  type="text/javascript" src="../../js/jquery-ui.js"></script>
    <script  type="text/javascript" src="../../js/jQuery-File-Upload-master/js/jquery.fileupload.js"></script>
    <script type="text/javascript" src="../../js/jQuery-File-Upload-master/js/vendor/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="../../js/jQuery-File-Upload-master/js/jquery.iframe-transport.js"></script>
    <script  type="text/javascript">
        $('#fileupload').fileupload({
            dataType : 'json',
            url : "ownmessages",
            add: function (e, data) {
                $('#post') .click(function () {
                    $('#post').text('Uploading...');
                    data.submit();
                });
            },
            done: function (e, data) {
                $('#post').text('Upload finished.');
            }
        });
    </script>
</head>
<body>
    <s:form action="ownmessages" enctype="multipart/form-data" method="post">
        <s:textarea rows="2" cols="40" name="message" id="message1"></s:textarea><br>
        <s:select name="msg_visibility" id="msg_visibility" list="#{'public':'Public', 'friends':'Friends','me':'Me only'}" value="public"/>
        <input id="fileupload" type="file" name="user_post_image[]"  data-url="ownmessages"/>
        <input type="button" value="Post" id="post" />
    </s:form>
</body>

Solution

  • You need to wait for the document to finish loading before you try and select any elements. The jQuery .ready() method waits for the Document Object Model (DOM) to finish loading and then runs your script.

    $(document).ready(function() {
      $('#fileupload').fileupload({
            dataType : 'json',
            url : "ownmessages",
            add: function (e, data) {
                $('#post') .click(function () {
                    $('#post').text('Uploading...');
                    data.submit();
                });
            },
            done: function (e, data) {
                $('#post').text('Upload finished.');
            }
        });
    });
    

    Instead of using .ready() you can also just pass a function to jQuery.

    $(function() {
        // will run after DOM is loaded
    });