2

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.

1 Answer 1

6

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(); }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.