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 ?