如何在不刷新页面的情况下在同一{div}上显示表单成功消息?

时间:2019-05-31 08:38:50

标签: php jquery html ajax form-submit

如何在不刷新页面的情况下在同一表单上提交表单?在这里,我要提交一个pdf来拖放容器,当我提交表单时,它会重定向到upload.php。我需要在同一容器上显示成功消息。我对ajax的了解不足。请帮助我解决问题

这是下面的拖放容器:

enter image description here

以下是结果页(upload.php)

enter image description here

HTML表单:

<form method="POST" action="upload.php" enctype="multipart/form-data">
  <input type="file" multiple name="file[]" accept="application/pdf">
      <input class="button-primary" type="submit" value="Submit">
</form>

Upload.php文件:

<?php 
//echo 'done';
$output = '';

    if(isset($_FILES['file']['name'][0])){
        //echo 'ok';
        foreach($_FILES['file']['name'] as $keys => $values) {

            if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'upload/' .$values)) {

                $output .= 'Form submited succesfully';
            }
        }
    }
echo $output;
?>

2 个答案:

答案 0 :(得分:0)

使用以下代码

<form method="POST" enctype="multipart/form-data">
            <input id='file' type="file" multiple name="file[]" accept="application/pdf">
            <input id='submit'class="button-primary" type="submit" value="Submit">
        </form>
 $("#submit").submit(function(e){
    e.preventDefault();
 var xhr = new XMLHttpRequest();
          var data = new FormData();

          data.append("file",document.getElementById("file").files[0]);
          xhr.open("post","/upload.php",true);

          xhr.send(data);


            });

答案 1 :(得分:0)

您可以防止表单在提交时的默认行为,该行为会将其重定向。 尝试使用此:

kms:*

现在,您可以在想要显示的任何位置显示所需的消息。我在这里显示了ID为<form id="form" method="POST" enctype="multipart/form-data"> <input id='file' type="file" multiple name="file[]" accept="application/pdf"> <input class="button-primary" type="submit" value="Submit"> </form> <p id="response-text"></p> <script> $("#form").submit(function (e) { e.preventDefault(); var xhttp = new XMLHttpRequest(); var data = new FormData(); data.append("file", document.getElementById("file").files[0]); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById("response-text").innerHTML = 'Form Successfully Submitted'; } else { document.getElementById("response-text").innerHTML = 'Form could not be submitted'; } }; xhttp.open("post", "/upload.php", true); xhttp.send(data); }); </script> 的{​​{1}}