0

I want to post with the Fetch API and call an action from my controller but the action is not being loaded like when I would do it with submitting a post form.

function postQuery() {
      let query = document.getElementById("query").value;

      fetch('/actionName', {
          method: 'POST',
          body: query,
          headers:
              {
                  "Content-Type": "application/x-www-form-urlencoded"
              }
      })
          .then(response => {
              console.log(response);
          })
          .then(data => {
              console.log('Success:', data);
          })
  }

/actionName is not being loaded, I am supposed to be directed to a different page.

When I would submit a form like that:

<form action="/actionName" method="post">

the public function actionName would be called but with fetch its not working. When i try to see the $_POST with var_dump($_POST) inside of actionName, I am getting an empty array...I dont understand this

1
  • What do you mean by "action"? Can you post some code? Commented Oct 23, 2020 at 14:39

1 Answer 1

0

I see two questions here:

  1. Why is the data not accessible to the server
  2. Why is the brower not redirected to /actionName

Answer to #1:

Make sure the content type header matches the data you are sending, if it is raw json, you should use application/json rather then application/x-www-form-urlencoded. If you want to send a form using fetch API, you would need to either serialize to form to a URL encoded format, or use FormData, for example:

var fd = new FormData(document.getElementById('myForm'))
fetch('/actionName', {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data;'
  },
  body: fd
})

Answer to #2:

Submitting HTML Forms will direct the browser to the forms action, so if I submit a form to /actionName, I will end up seeing the HTML that is returned by the server for that route. Using Fetch API to submit a form is a type of AJAX, which means that it is capable of communicating with the server without needing to load a new page.

With that in mind, you have a few options:

  • Use a regular form so that the desired default behavior happens
  • Manually redirect the user somewhere after the fetch promise resolves, something like:
fetch(/*..*/).then(data => {
  console.log('Success:', data);
  window.location.href = '/otherPage'
})
  • Render the response HTML without redirecting the user, something like:
fetch(/*..*/).then(data => {
  console.log('Success:', data);
  data.text().then(rawHTML => {
    document.body.parentElement.innerHTML = rawHTML
  })
})

My personal intuition would be to go with the first option, as it suits your requirements and is the simplest.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. With window.location.href = '/otherPage' I am getting redirected. But how can i access the $_POST inside of the public function /otherPage ? When i write var_dump($_POST), I am getting an empty array
As stated in my answer, I believe you have a content type mismatch. You should either change the content type header to match your data format, or you should change your data to match the header. If you add the value of query to your question we will be able to help you more as we will then know what sort of data you are trying to send.
query is a string from user input in an input field. I changed headers to 'Content-Type': 'multipart/form-data;' and I also tried with 'Content-Type': 'text/html;' but var_dump[$_POST] is still empty
This question should help explain, looks like there is some weirdness with how PHP will handle different incoming data formats.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.