Search code examples
javascriptjqueryhtmlform-data

Uncaught TypeError: Cannot read property 'files' of null of element


I am creating a little website that has chats on it. Currently, one can only send text messages and I wanted to open a file sender as well for sending image(s), video(s), gif(s).

I have encountered a few problems along the way, but so far got everything without the support of others. However, I am in great need of it now.

By using FormData, Ajax and jQuery, I am able to have real-time images sent from the client to the PHP server. The problem that I am facing is:

Uncaught TypeError: Cannot read property 'files' of null

when trying to append a file to formData. Take a look:

function opencraze() {
    $(".browse_send_file").change(function () {
        var chat_id = "123";
        var formData = new FormData();

        formData.append("chat_id", chat_id);

        var name = document.getElementById('#browse_' + chat_id);
        var filemsg = name.files[0];
        formData.append("userfile", filemsg);
    });
}

The HTML:

<div class="chat_wcom" style="width: 25%;">
    <label for="browse_123" class="material-icons"></label>
    <input type="file" class="browse_send_file" id="browse_123" name="browse_send_file" style="display: none">
    <input maxlength="140" type="text" id="input_123" class="comin" placeholder="My message..." name="sendmsg" onkeypress="g(event,123)" autocapitalize="off" autocorrect="off" style="width: auto;">
    <input class="hidden_index" type="text" value="123" name="chat_index">
</div>

What happens before everything is that when the user clicks on a div, this HTML above is generated and once it is generated, it calls the opencraze() function. Now, if one presses on the label of the chat, one selects the file and it activates the .change() jQuery function. The error is on the line of:

var filemsg = name.files[0];

Any help would be appreciated. Thank you for your time.


Solution

  • The native javascript document.getElementById() expects the 'id' as string without the jQuery selector #.
    So remove the #:

    var name = document.getElementById('browse_'+chat_id);
    

    Or use the jQuery selector method:

    var name=$('#browse_'+chat_id);