1

I am not front end developer and I'm spending a quite time trying to do so. Hope you guys can help me. I have a form which sends files to an API in server, like below:

<form id="uploadForm" action="url/upload/" method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1">   

      <div class="inputFileCustom">
        <input type="file" size="45" name="file" id="uploadFiles" accept="application/pdf"/>
        <label for="uploadFiles">
            <div class="ic-bt ic-bt-details ic-bt-text btn btn-border">
            Choose a file
            </div>
        </label>
    </div>

    <input type="submit" value="Upload PDF" class="btn btn-primary" />
</form>

url/upload returns a JSON, like:

{ "status": "ok"/"fail" }

I need two things:

  1. Prevent submit to redirect to url/upload;
  2. Get JSON response from server and, if successful, call loadFiles() function (which is already working).

I'm using javascript for loadFiles() function, but its very simple.

Leonardo
  • 1,263
  • 7
  • 20
  • 51

4 Answers4

4

You can use jquery form handler as,

<script>     

    // Attach a submit handler to the form 
  // Attach a submit handler to the form 


$("#uploadForm").submit(function(event) {

    var formData = new FormData();
    formData.append("uploadFiles", $('[name="file"]')[0].files[0]);
    event.stopPropagation();
    event.preventDefault();
    $.ajax({
      url: $(this).attr("action"),
      data: formData,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function(data) {
        alert(data);
        loadFiles()
      }
    });
    return false;
  });

    </script>

Refer this stackoverflow question

Community
  • 1
  • 1
Shankar Gurav
  • 1,057
  • 9
  • 17
2

It looks like you need to post the request using Javascript. If you're using JQuery, you can use $.ajax for example:

$.ajax({
    url: '',
    type: '',
    data: {},
    success: function(data){
        console.log(data);
    }
})

Using this means that it won't redirect the page away from the form, so that you can display success or error messages to the same screen.

See http://api.jquery.com/jquery.ajax/ for more information

Luke P
  • 723
  • 7
  • 19
  • That is a server side error, so either its expecting a parameter you're not passing, or it's something else server side. Ajax is the right solution, using the code above it will make a request to the server and log out the response. – Luke P Mar 02 '16 at 18:22
0

Check this fiddle: https://jsfiddle.net/41mnz0z1/

$('#uploadForm').submit(function(e) {
    e.preventDefault();
    $.ajax({
        url: '/echo/json/',
        data: $(this).serialize(),
        type: 'POST',
        success: function(data) {
            alert(data);
        }
    });
});

e.preventDefault() prevents the standard action of the browser after submitting the form (redirecting you to another page). data: $(this).serialize() sends the form data to your desired url: 'fileUpload.php'.

It works the same with a file.

Michael Röhrig
  • 120
  • 1
  • 10
  • This is not working. I don't know how server is getting this request but using `$(this).serialize()` returns an error. If I use filename in URL property (url + fileToPost) it returns Bad Request. – Leonardo Mar 03 '16 at 14:55
-1
1. Prevent submit to redirect to url/upload    

    <form id="uploadForm" action="url/upload/" method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1" onsubmit ='return checkRegistration()'>   

              <div class="inputFileCustom">
                <input type="file" size="45" name="file" id="uploadFiles" accept="application/pdf"/>
                <label for="uploadFiles">
                    <div class="ic-bt ic-bt-details ic-bt-text btn btn-border">
                    Choose a file
                    </div>
                </label>
            </div>

            <input type="submit" value="Upload PDF" class="btn btn-primary" />
        </form>


     <script>
        function checkRegistration(){
            if(!form_valid){           
                return false;
            }
            return true;
        }
        </script>
Santosh Ram Kunjir
  • 1,074
  • 1
  • 12
  • 23