Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  37] [ 7]  / answers: 1 / hits: 28069  / 8 Years ago, wed, march 2, 2016, 12:00:00

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.


More From » html

 Answers
66

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


[#63078] Monday, February 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;