0

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me. There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former. So, the code:

<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" --> <label>Name</label> <input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br> <label id="nameerror"></label><br> <label>Email</label> <input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br> <label id="emailerror"></label><br> Select a file<br /> <label id="draganddroperror"></label><br> <input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br /> <button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button> </form> 

There is my JS

function sendData() { var file_data = $("#fileToUpload").prop("files"); console.log(file_data); if ($("#file_data").val() != "") { var form_data = new FormData(); //form_data.append('file', file_data); //console.log(file); form_data.append('file', file_data); console.log(form_data); $.ajax({ url: 'uploadfile.php', // point to server-side PHP script dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(data) { // get server responce here //alert(data); // clear file field //$("#your-files").val(""); return false; } }); return false; //event.preventDefault(); } else { alert("Please select file!"); } } 

So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere. I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.

9
  • Shouldn't your return false be after the else clause? Commented Jan 25, 2018 at 23:34
  • I don't think so. else clause don't post anything. Commented Jan 25, 2018 at 23:36
  • The click event of the <button> is a post action by itself. Commented Jan 25, 2018 at 23:38
  • 1
    I don't think you understand why you would return false. You basically haven't tried anything in that post you referenced. I don't see you preventing the default action on the event (that you didn't bother to pass in to the click handler). I don't see you returning false to prevent the default action either. Commented Jan 25, 2018 at 23:38
  • When you don't have <button type="submit"></button> inside your form, every button acts as type="submit" Commented Jan 25, 2018 at 23:40

4 Answers 4

1

The trick to prevent form submission is return false onsubmit as below:

<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data"> <!--action="uploadfile.php" onsubmit="return false;" --> <label>Name</label> <input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /> <br> <label id="nameerror"></label> <br> <label>Email</label> <input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" /> <br> <label id="emailerror"></label> <br> Select a file <br /> <label id="draganddroperror"></label> <br> <input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /> <br /> <button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button> </form> 

Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.

function sendData() { var file_data = $("#fileToUpload").prop("files"); console.log(file_data); if ($("#file_data").val()) { var form_data = new FormData(); //form_data.append('file', file_data); //console.log(file); form_data.append('file', file_data); console.log(form_data); $.ajax({ url: 'uploadfile.php', // point to server-side PHP script dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(data) { // get server responce here //alert(data); // clear file field //$("#your-files").val(""); } }); } else { alert("Please select file!"); } return false; } 

I hope this gives you the clear understanding.

Sign up to request clarification or add additional context in comments.

1 Comment

I accept your answer, because it's clear for understanding and simple for reproduce. Though, I should notice, that with that combination of my JS, your code and my PHP code on a backend it breaks the backend program. Somehow it sends to PHP empty sctructures and while I get from PHP some alerts, program the backend doesn't work as it meant to be.
0

You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.

var submitButton = document.getElementById('btnSubmit'); submitButton.addEventListener('click', sendData); // Then you will have access to the event in the sendData function function sendData(ev) { ev.preventDefault(); ... } 

Live example

A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.

var form = document.getElementById('form'); form.addEventListener('submit', sendData); 

Live example

5 Comments

got an error: Cannot read property 'preventDefault' of undefined on ev.preventDefault(); line
Did you remove the HTML onclick attribute and add the provided Javascript code?
Removed. Not it doesn't post, though there no errors in console. Added <input id="btnSubmit" type="submit" style="background-color: gray; color: #ffffff;" value="Send files" /> <button id="btnSubmit2" style="background-color: gray; color: #ffffff;" />Отправить</button> to handle form.
My Codepen example is working just fine, so I don't know what is going wrong on your end.. You could make a codepen with the code you currently have so I could try to find your mistake.
It doesn't work for me neither on codepen neither locally. Don't fire any console.log (I opened console) messages or alerts(). Probably I just to tired. On both codepens (button click on the first, enter presskey on the second).
0

In function sendData() you should pass event param like this

 function sendData(evt) { } 

and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.

Comments

0

Add type attribute with the value of button and you are done:

<button id="btnSubmit" type="button" ... 

By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

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.