Ajax jquery cakephp 3

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

1 Like

Please, send code of your action.

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. });

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() ?>
1 Like

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.

1 Like

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

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

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

Will just not work.

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.

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

A good starting point is:

1 Like

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?

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