user2918057
user2918057

Reputation: 199

ajax form doesn't work

I've issues in my code, I need send an image with ajax, but when I'd in my code, doesn't work.

I'll need use forms for validated my servlets.

 <script type="text/javascript">

      function UploadFile() {

          fileData = document.getElementById("filePicker").files[0];
          var data = new FormData();

          var url = 'localhost';

          console.log(url);
          alert(url);

          $.ajax({
              url: url,
              type: 'POST',
              data: fileData,
              cache: false,
              crossDomain: true,
              dataType: 'json',
              processData: false,
              contentType: false,
              success: function (data) {
                  alert('successful..');
              },
              error: function (data) {
                  alert('Ocorreu um erro!');
              } 
          });
          alert("Finalizou");
      }
    </script>

    <body>
       <form>
            <input type="file" id="filePicker" value="" />
            <button id="btnUpload" onclick="UploadFile()">Upload</button>
       </form>
    </body>

If I'd remove the form like that.

<body>
   <input type="file" id="filePicker" value="" />
   <button id="btnUpload" onclick="UploadFile()">Upload</button>
</body>

It's works.

Upvotes: 2

Views: 90

Answers (1)

adeneo
adeneo

Reputation: 318182

A button element will be of type submit as default, so it will submit the form and reload the page.
You have to prevent that, something like this

<form>
    <input type="file" id="filePicker" value="" />
    <button id="btnUpload" onclick="UploadFile(); return false;">Upload</button>
</form>

but as you're using jQuery, you should remove the inline javascript and use proper event handlers

$(function() {
    $('#btnUpload').closest('form').on('submit', function(e) {
        e.preventDefault();
        UploadFile();
    });
});

Upvotes: 6

Related Questions