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.

Washington Guedes
  • 4,254
  • 3
  • 30
  • 56
Areso
  • 67
  • 1
  • 2
  • 11
  • Shouldn't your `return false` be after the `else` clause? – Washington Guedes Jan 25 '18 at 23:34
  • I don't think so. else clause don't post anything. – Areso Jan 25 '18 at 23:36
  • The click event of the ` – Washington Guedes Jan 25 '18 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. – gforce301 Jan 25 '18 at 23:38
  • When you don't have `` inside your form, every button acts as `type="submit"` – Washington Guedes Jan 25 '18 at 23:40
  • preventDefault - tried, then nothing post at all. It wasn't in code or in comments . "return false" originally weren't in my code. Tried to delete action from Form title, got server error. – Areso Jan 25 '18 at 23:41
  • Are you able to put the button outside of the form? That way, I believe it won't trigger the submit action. @WashingtonGuedes is right. – Gordon Kushner Jan 25 '18 at 23:42
  • @GordonKushner moved button outside the form. Still got redirect – Areso Jan 25 '18 at 23:47
  • you can find a solution here https://stackoverflow.com/questions/2825856/html-button-to-not-submit-form – Firas Omrane Jan 25 '18 at 23:59

4 Answers4

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.

Kamal Singh
  • 990
  • 8
  • 13
  • 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. – Areso Jan 27 '18 at 19:15
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.

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

Niels de Bruin
  • 705
  • 5
  • 15
  • got an error: Cannot read property 'preventDefault' of undefined on ev.preventDefault(); line – Areso Jan 25 '18 at 23:55
  • Did you remove the HTML `onclick` attribute and add the provided Javascript code? – Niels de Bruin Jan 25 '18 at 23:56
  • Removed. Not it doesn't post, though there no errors in console. Added Отправить to handle form. – Areso Jan 26 '18 at 00:09
  • 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. – Niels de Bruin Jan 26 '18 at 00:17
  • 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). – Areso Jan 26 '18 at 00:32
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

YouneL
  • 8,152
  • 2
  • 28
  • 50