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

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 ?

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

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’]);’

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 ?

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