edddd
edddd

Reputation: 482

Do PHP form submissions cause the whole file to refresh?

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?

Upvotes: 0

Views: 47

Answers (1)

SMAKSS
SMAKSS

Reputation: 10520

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
    });
});

Upvotes: 2

Related Questions