1

I want to pass a file from a file input form to a php script via ajax and process the message my php script echoes.
This is my html form:

<form id="fileUploadForm"  method="POST" enctype="multipart/form-data">
  <input name="fileToUpload" id="fileToUpload" type="file">
  <button type="submit" name="submit" id="submit">Upload</button>
</form>

my js code:

$('#submit').click(function() {
  var file_data = $('#fileToUpload').prop('files')[0];
  var form_data = new FormData();
  form_data.append('fileToUpload', file_data);
  $.ajax({
    url: 'form.php',
    dataType: 'text',
    data: form_data,
    processData: false,
    contentType: false,
    type: 'post',
    success: function(data) {
      alert(data);
    },
});

and my (simplified) php script:

<?php
  //some code
  if(fileTooLarge){
    echo "Your file is too large!";
  }
  if(success){
    echo "Your file has been uploaded";
  }
?>

What I want to achieve is the the user gets a message if the file was uploaded successfully or it was too big/ had wrong extension without reloading the page.

0x1234
  • 101
  • 2
  • 11
  • 1
    `` change type to `button` – guradio Jul 05 '16 at 09:16
  • try `console.log()` instead of `alert()`, then look at your console in the developer tools to see what the structure of `data` is. – Moak Jul 05 '16 at 09:17
  • 1
    Note that it's much better to check the filesize *before* uploading the file, otherwise you have to wait for the entire file to upload to the server before being told that it's invalid. See [this question](http://stackoverflow.com/questions/3717793/javascript-file-upload-size-validation) for how to do that – Rory McCrossan Jul 05 '16 at 09:19
  • as @ Rory McCrossan its better to check file size before uploading – user3386779 Jul 05 '16 at 09:20
  • @guradio seems like that did the trick. I have too look further into it, but at least I'm getting something back instead of nothing. Can you explain why it makes a difference, because it seems a bit confusing to me? – 0x1234 Jul 05 '16 at 09:28
  • 1
    Changing the button type worked because your original code was submitting the form normally and ignoring the AJAX request. You could also have fixed this by hooking your event to the `submit()` event of the form and using `e.preventDefault()` – Rory McCrossan Jul 05 '16 at 09:28
  • 1
    @0x1234 because the type is submit and it is in form it is doing the default function of a button type submit not the ajax one – guradio Jul 05 '16 at 09:29
  • @RoryMcCrossan yes, I have done it that. It just looks like I first upload it and then check for file size because I wrote more like pseudo-code instead of real code. Also thanks for you explanation. – 0x1234 Jul 05 '16 at 09:34
  • How do I mark my question as solved now? Should I answer it myself? – 0x1234 Jul 05 '16 at 09:39
  • @0x1234 i posted an answer :) – guradio Jul 05 '16 at 09:58

3 Answers3

1

<button type="submit" name="submit" id="submit">Upload</button> change type to button

  1. Because the type is submit and it is in form it is doing the default function of a button type submit not the ajax one
guradio
  • 15,524
  • 4
  • 36
  • 57
  • Here you go :D. Btw are there any advantages or disadvantages using this method or the e.preventDefault() method @Rory McCrossan also suggested? – 0x1234 Jul 05 '16 at 10:13
  • @0x1234 happy it worked for you mate happy coding :) – guradio Jul 05 '16 at 10:14
0

you can change your js code to :

$('#submit').click(function(evt) {
evt.preventDefault();
...

or you can change the type of your input to button instead of submit

Hicham Zouarhi
  • 1,030
  • 1
  • 18
  • 28
0

If you want to achieve this, you can try this on client side in modern browsers. It works fine for me. In W3c File object inherit from Blob the property 'size'. https://www.w3.org/TR/FileAPI/#dfn-Blob

Tested in chrome last update.

<!DOCTYPE html>
<html>
<head>
    <title>InputFileTest</title>

    <!--<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
    <script type="text/javascript" src="inputFile.js"></script>!-->

    <script type="text/javascript">

        function validateSize(pFile){

            if (pFile.files[0].size > 9999999999999) {
                alert("Your file is not valid, it exceed our limit!")
                return false
            } 

            return true
        }

        function validateExtension(pFile){
            var fileName = pFile.files[0].name;
            var extension = "";

            for (var i = fileName.length - 1; i >= 0; i--) {

                if (fileName[i] == ".") {
                    break
                } else {
                    extension = fileName[i] + extension;
                }
            }

            if (extension == "bmp") {
                alert("Extension not permited!")
                return false;
            }

            return true;
        }

        function validatingFile(){
            var file = document.getElementsByClassName("file")[0];
            if (file.files.length > 0) {
                valid = validateSize(file);
                valid = validateExtension(file);

                if (valid) {

                    alert("Upload it!");

                }
            } else {
                alert("Select a valid file!");
            }
        }

    </script>
</head>

<body>

    <input type="file" name="file" class="file">
    <button onclick="validatingFile()">Sumit</button>

</body>
</html>
Pimptech
  • 95
  • 10