# \[Solved\]Using Fetch API return 404 how to test Ajax request in CakePHP 4

**URL:** <https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713>\
**Category:** Need Help\
**Created:** [April 23, 2020, 7:34pm UTC](https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713 "2020-04-23T19:34:55Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![christ57](https://avatars.discourse-cdn.com/v4/letter/c/b4bc9f/32.png) [@christ57](https://discourse.cakephp.org/u/christ57)\
**Post date:** [April 23, 2020, 7:34pm UTC](https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713/1 "2020-04-23T19:34:55Z")

</div>

Hello,

I want to use Fetch API to send form data to my Controller.

Here’s my javascript code

```
let form = document.querySelector('#form_tweet')

let button = form.querySelector('button[type=submit]')

let buttonText = button.textContent

form.addEventListener('submit', async function (e) {

button.disabled = true

 button.textContent = 'Chargement...'

e.preventDefault();

let data = new FormData(this)

console.log(form.getAttribute('action'));

let response = await fetch(form.getAttribute('action'), {
  method: 'POST',
  body: data
}).then(function(response) {
	
  return response.json();
}).then(function(data) {
  alert('form submited')
}).catch(function(err) {
  //Failure
  alert(err)
});
button.disabled = false
button.textContent = buttonText
})

```

And my Controller

```
/**
 * Add method
 *
 * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
 */
public function add()
{
        if ($this->request->is('ajax'))
    {
        
    $tweet = $this->Tweets->newEmptyEntity();
    

                    $idtweet = $this->idtweet(); // génération d'un nouvel identifiant de tweet

            $data = array(
                            'id_tweet' => $idtweet,
                            'user_tweet' => $this->Auth->user('username'),
                            'user_timeline' => $this->Auth->user('username'),
                            'contenu_tweet' => $this->request->getData('contenu_tweet'),
                            'nb_commentaire' =>0,
                            'nb_partage' =>0,
                            'nb_like' =>0,
                            'private' =>0,
                            'allow_comment' => 0
                        );

            $tweet = $this->Tweets->patchEntity($tweet, $data);

        //$tweet = $this->Tweets->patchEntity($tweet, $this->request->getData());
        if ($this->Tweets->save($tweet)) {
            $this->Flash->success(__('The tweet has been saved.'));

            //return $this->redirect(['action' => 'index']);
            $this->response->withStringBody(json_encode($tweet)); // réponse AJAX pour affichage
        }
        else
        {
             $this->Flash->error(__('The tweet could not be saved. Please, try again.'));
              $reponse = 'probleme'; // impossible d'ajouter ce tweet
                $this->response->withStringBody($reponse);
        }
       
       return $this->response; // envoi d'une réponse AJAX
    
    $this->set(compact('tweet'));
}
 
        else
    {
        throw new NotFoundException(__(This page doesnt exist.'));
    }

}

```

I always got The Notfound Exception Can you help me ?

---

<div class="post-metadata">

**Author:** ![dreamingmind](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/dreamingmind/32/1857_2.png) [@dreamingmind](https://discourse.cakephp.org/u/dreamingmind)\
**Post date:** [April 23, 2020, 8:13pm UTC](https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713/2 "2020-04-23T20:13:55Z")

</div>

What is the actual value of `form.getAttribute('action')`?

---

<div class="post-metadata">

**Author:** ![christ57](https://avatars.discourse-cdn.com/v4/letter/c/b4bc9f/32.png) [@christ57](https://discourse.cakephp.org/u/christ57)\
**Post date:** [April 24, 2020, 7:07am UTC](https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713/3 "2020-04-24T07:07:28Z")

</div>

Hello,

The actual value is ‘/website/tweet/add’.

If I don’t use Ajax (classic form submission) it works.

The route above to was configured in my routes file as well : ‘$builder-\>connect(’/tweet/add’,[‘controller’ =\> ‘Tweets’, ‘action’ =\> ‘add’]);’

---

<div class="post-metadata">

**Author:** ![christ57](https://avatars.discourse-cdn.com/v4/letter/c/b4bc9f/32.png) [@christ57](https://discourse.cakephp.org/u/christ57)\
**Post date:** [April 24, 2020, 8:52am UTC](https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713/4 "2020-04-24T08:52:32Z")

</div>

I no longer have a 404 error if I do not do the ajax request test at the start of the controller.

But i need to do this test

is there a new way to test if the request is in ajax with cakephp 4 ?

---

<div class="post-metadata">

**Author:** ![christ57](https://avatars.discourse-cdn.com/v4/letter/c/b4bc9f/32.png) [@christ57](https://discourse.cakephp.org/u/christ57)\
**Post date:** [April 24, 2020, 12:11pm UTC](https://discourse.cakephp.org/t/solved-using-fetch-api-return-404-how-to-test-ajax-request-in-cakephp-4/7713/5 "2020-04-24T12:11:38Z")

</div>

Solved by sending ‘X-Requested-With’: ‘XMLHttpRequest’ in headers option.
