Do PHP form submissions cause the whole file to refresh?

笑着哭i 提交于 2021-01-29 05:38:34

问题


Will using <form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post"> cause the whole page to refresh when the user clicks submit? Or just the PHP part?


回答1:


The page usually will reload after submitting a form to display the response that is received after submitting the form.

To prevent that you got two ways:

  1. Use target=_blank in your form tag
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" target="_blank">
  1. Use event.preventDefault(); to prevent the default action of form and then send data manually with fetch or if you use JQuery you might go with ajax. (I will go with fetch standard API)
document.getElementByTagName("form")[0].addEventListener('submit', function(event) {
  event.preventDefault();

  const url = 'https://randomuser.me/api';
  // The data we are going to send in our request
  const data = {
    name: 'Sara'
  }
  // The parameters we are gonna pass to the fetch function
  const fetchData = {
    method: 'POST',
    body: data,
    headers: new Headers()
  }
  fetch(url, fetchData)
    .then(function() {
      // Handle response you get from the server
    });
});


来源:https://stackoverflow.com/questions/61586898/do-php-form-submissions-cause-the-whole-file-to-refresh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!