# Ajax jquery cakephp 3

**URL:** <https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294>\
**Category:** Need Help\
**Created:** [February 17, 2020, 11:13am UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294 "2020-02-17T11:13:11Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![schloter](https://avatars.discourse-cdn.com/v4/letter/s/a183cd/32.png) [@schloter](https://discourse.cakephp.org/u/schloter)\
**Post date:** [February 17, 2020, 11:13am UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/1 "2020-02-17T11:13:11Z")

</div>

i want to send the data by ajax jquery to my cakephp 3 controller action but i have a 403 forbiden how to send the data by ajax jquery on cakephp 3.  
Please help me, thanks

---

<div class="post-metadata">

**Author:** ![ilyav](https://avatars.discourse-cdn.com/v4/letter/i/c4cdca/32.png) [@ilyav](https://discourse.cakephp.org/u/ilyav)\
**Post date:** [February 17, 2020, 1:03pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/2 "2020-02-17T13:03:34Z")

</div>

Please, send code of your action.

---

<div class="post-metadata">

**Author:** ![schloter](https://avatars.discourse-cdn.com/v4/letter/s/a183cd/32.png) [@schloter](https://discourse.cakephp.org/u/schloter)\
**Post date:** [February 17, 2020, 3:08pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/3 "2020-02-17T15:08:14Z")

</div>

here is my action controler :  
public function setLigne()  
{  
if($this-\>request-\>is(‘Potsr’))  
{  
$this-\>autorender = false;

```
		$idLigne = $this->request->data['idLigne'];
		$donnee = $this->request->data['donnee'];
		$valeur = $this->request->data['valeur'];

		if($donnee == "date_debut_contrat")
		{
			$this->Marches->setDateDebut($idLigne, $valeur);
		}
		if($donnee == "date_fin_contrat")
		{
			$this->Marches->setDateFin($idLigne, $valeur);
		}
	}
	
	return true;

```

my function ajax  
var semaphoreChargementAjax = 0;  
var debug = true;

function ajax(url, variables, elementCible, msgErreur, eleChargement, methode) {  
//Si on a passé un élément à afficher durant le chargement  
if(eleChargement !== undefined) {  
$(’#’+eleChargement).fadeIn();  
window.semaphoreChargementAjax ++;  
}  
console.log(url);  
console.log(variables)  
if (url === undefined)  
return false;

/\* Conversion du tableau associatif des variables en une chaîne pour envoie HTTP \*/  
var chaineVariables = “”;  
var i = 0;  
for (var key in variables) {  
//Cas de la dernière valeur du tableau -\> on n’ajoute pas le caractère ‘&’  
if(Object.keys(variables).length - 1 == i)  
chaineVariables += key + “=” + variables[key];  
else  
chaineVariables += key + “=” + variables[key] + “&”;

```
i++;

```

}

//Si le paramètre méthode est incorrecte, on utilise POST par défaut  
if (! (methode == ‘POST’ || methode == ‘GET’) )  
methode = ‘POST’;

.ajax({ url : url, data : chaineVariables, type : methode, dataType : 'html', success : function(code\_html) { if(elementCible !== undefined) (’#’+elementCible).html(code\_html);

```
  if(eleChargement !== undefined)
    window.semaphoreChargementAjax --;

  if(window.semaphoreChargementAjax <= 0) {
    $('#'+eleChargement).fadeOut();
    window.semaphoreChargementAjax = 0;
  }
  
},
error : function() {
  // if (msgErreur !== undefined && msgErreur != null && debug)
  // alert(msgErreur);

  if(eleChargement !== undefined && eleChargement != null)
    window.semaphoreChargementAjax --;

  if(window.semaphoreChargementAjax <= 0) {
    $('#'+eleChargement).fadeOut();
    window.semaphoreChargementAjax = 0;
  }
}

```

});

return true;  
}

call from my function in my view :

 $(function(){ $('#set-date-debut').click(function(){ var data = { idLigne: "\<?php echo $marches-\>num\_contrat ?\>", donnee: "date\_debut\_contrat", valeur: $('#date-debut').val(), }; data.valeur = data.valeur.split("/")[2]+"-"+data.valeur.split("/")[1]+"-"+data.valeur.split("/")[0]; ajax("eprestaLorraine/Marches/setLigne", data, null, "Erreur", null, 'post'); // send data to the setLine function. });

---

<div class="post-metadata">

**Author:** ![ilyav](https://avatars.discourse-cdn.com/v4/letter/i/c4cdca/32.png) [@ilyav](https://discourse.cakephp.org/u/ilyav)\
**Post date:** [February 17, 2020, 3:49pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/4 "2020-02-17T15:49:25Z")

</div>

Sorry, I cannot understand your code. There is my solution, maybe it can be useful. Example with form and jQuery.

**JS:**

```
$('.submitButton').click(function(event) {
    //logic with processing data from view
    $.ajax({
        type: 'POST',
        data: data,
        url: /* link to controller action*/,
    })
    .done(function(result) {
        //if from controller return 200 status code
    })
    .fail(function(result) {
        //if from controller return 400 status code
    })
});

```

**Controller:**

```
public function myAction() {
    if ($this->request->is('ajax')) {
        $this->response->type('json');
        $this->response->statusCode(200);
        $response = $this->response;
        $response->Body(json_encode([
            'message' => 'message'
        ]));
        return $response;
    }
}

```

**View:**

```
<?= $this->Form->create(null, ['url' => ['action' => 'myAction']) ?>
    <fieldset>
        //you fields
    </fieldset>
    <?= $this->Form->button(__('Submit'), ['class' => 'submitButton']) ?>
<?= $this->Form->end() ?>
```

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [February 17, 2020, 10:06pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/5 "2020-02-17T22:06:45Z")

</div>

Formatting of the code isn’t so helpful, put ``` on a line by itself before and after the code block to make that more readable, that will make it more likely that people will even bother to try to read through it to help you.

---

<div class="post-metadata">

**Author:** ![schloter](https://avatars.discourse-cdn.com/v4/letter/s/a183cd/32.png) [@schloter](https://discourse.cakephp.org/u/schloter)\
**Post date:** [March 2, 2020, 10:11am UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/6 "2020-03-02T10:11:12Z")

</div>

sorry for responding late.  
Ilyav I used your method, but I now have an error 500, I do not understand how a simple request ajax in post can generate this error, I search by everything on the internet, but kidney does not change, I am really short idea. how can an ajax jquery request work in cakephp 2 and not in cakephp 3? Help me please

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [March 2, 2020, 4:40pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/7 "2020-03-02T16:40:09Z")

</div>

Details of any 500 error should be in your logs. There’s too many possible reasons for us to guess without those details.

---

<div class="post-metadata">

**Author:** ![MarceliSzpak](https://avatars.discourse-cdn.com/v4/letter/m/4af34b/32.png) [@MarceliSzpak](https://discourse.cakephp.org/u/MarceliSzpak)\
**Post date:** [March 2, 2020, 5:19pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/8 "2020-03-02T17:19:48Z")

</div>

Response / Request are immutable objects.  
Code between :  
if ($this-\>request-\>is(‘ajax’)) {  
.  
}

Will just not work.

---

<div class="post-metadata">

**Author:** ![schloter](https://avatars.discourse-cdn.com/v4/letter/s/a183cd/32.png) [@schloter](https://discourse.cakephp.org/u/schloter)\
**Post date:** [March 3, 2020, 9:22am UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/9 "2020-03-03T09:22:12Z")

</div>

> [@Zuluru](#):
>
> Details of any 500 error should be in your logs. There’s too many possible reasons for us to guess without those details.

thank you for you reply. I looked at my cake log file here are the error messages I got:  
2020-03-03 08:27:24 Error:  
[Cake\Http\Exception\InvalidCsrfTokenException] CSRF token mismatch. (/appli/projects/dr-lorraine/apache\_2.4/htdocs/dr-lorraine/eprestaLorraine/vendor/cakephp/cakephp/src/Http/Middleware/CsrfProtectionMiddleware.php:232) and  
#9 /appli/projects/dr-lorraine/apache\_2.4/htdocs/dr-lorraine/eprestaLorraine/vendor/cakephp/cakephp/src/Http/Runner.php(65): Cake\Error\Middleware\ErrorHandlerMiddleware-\>\_\_invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response), Object(Cake\Http\Runner))

I don’t understand this error.

---

<div class="post-metadata">

**Author:** ![Schlaefer](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/schlaefer/32/1001_2.png) [@Schlaefer](https://discourse.cakephp.org/u/Schlaefer)\
**Post date:** [March 3, 2020, 11:54am UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/10 "2020-03-03T11:54:48Z")

</div>

You’re using Cake’s CSRF protection. It prevents involuntary sending arbitrary data.

A good starting point is:

- [https://en.wikipedia.org/wiki/Cross-site\_request\_forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery)
- [https://book.cakephp.org/3/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware](https://book.cakephp.org/3/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware)
- And esp. [https://book.cakephp.org/3/en/controllers/middleware.html#csrf-protection-and-ajax-requests](https://book.cakephp.org/3/en/controllers/middleware.html#csrf-protection-and-ajax-requests)

---

<div class="post-metadata">

**Author:** ![schloter](https://avatars.discourse-cdn.com/v4/letter/s/a183cd/32.png) [@schloter](https://discourse.cakephp.org/u/schloter)\
**Post date:** [March 3, 2020, 2:59pm UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/11 "2020-03-03T14:59:58Z")

</div>

I tried to deactivate the CSRF like that :  
public function beforeFilter(Event $event)  
{  
$this-\>eventManager()-\>off($this-\>Csrf);  
}

but I still have error 500, does the Csrf automatically activate when creating a cake 3 project? shouldn’t we activate middleware before?

---

<div class="post-metadata">

**Author:** ![wakikuk](https://avatars.discourse-cdn.com/v4/letter/w/e95f7d/32.png) [@wakikuk](https://discourse.cakephp.org/u/wakikuk)\
**Post date:** [March 4, 2020, 12:11am UTC](https://discourse.cakephp.org/t/ajax-jquery-cakephp-3/7294/12 "2020-03-04T00:11:01Z")

</div>

Try dont active app debug, change to false, if error again u can add layout ajax on controller, if error again u must send token csrf from ajax…  
How to send csrf look this…  
First you u must request token or csrf with code  
json\_encode($this-\>request-\>getParam(’\_csrfToken’))  
Step two  
Get the value to variable javascript or var  
And send with data from ajax u can add  
headers:{‘X-CSRF-Token’:variable\_csrf }  
Good luck
