简体   繁体   中英

Prevent redirecting after post

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.

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM