Passing variable from ajax or jquery to element in cakephp in CakePHP 3.6


#1

Tengo un codigo que abre una página modal con jquery:

<div id="home-caja-datos">
      <div class="home-caja-dato">
        <span>Usario:</span> <?= $nombre; ?>
        &nbsp;&nbsp;<i id='modificar-nombre-cuenta' class="fa fa-pencil fa-sm" aria-hidden="true" title="Modificar nombre"></i>
      </div>
      <div class="home-caja-dato">
        <span>Email:</span>  <?= $email; ?>
        &nbsp;&nbsp;<i id='modificar-email-cuenta' class="fa fa-pencil fa-sm" aria-hidden="true" title="Modificar email"></i>
      </div>
      <div class="home-caja-dato">
        <span>Cambiar contraseña</span>
        &nbsp;&nbsp;<i id='modificar-password-cuenta' class="fa fa-pencil fa-sm" aria-hidden="true" title="Modificar contraseña"></i>
      </div>
      <div class="home-caja-dato">
        <span>Fecha de alta:</span> <?= $alta->nice('Europe/Madrid', 'es-ES'); ?>
      </div>
    </div>

$(document).on("click","#modificar-foto-cuenta", function() {
			if (esva === 0) {
				opcion = 1;
				$.ajax({
					async: true,
					cache: false,
					type: 'POST',
					url: modalHome,
					//method:"POST",
					dataType: 'json',
					data: {opcion: opcion},
					success: function(data) {
						alert(data);
						console.log(data);
					}
				});
				$('.modalHome').show();
			}
			else if (esva === 1) {
				$('.modalHome').hide();
				esva = 0;
			}
		});

What I want is to pass the variable “option” from jQuery to PHP, the only way is with AJAX.
“modalHome” es un element in CakePHP.
“modalHome” is found in the body outside the header, nav, section, etc.

<body> 
  <div class="modalHome">
    <?= $this->element('modalHome'); ?>
  </div>
  <header>

I want to recover the variable “option” either by POST or by GET in the modalHome element.

if(isset($_POST['opcion']) {
    $opcion = $_POST['opcion']);
    echo "OPCIÓN: ".$opcion;
  }

But it doesn’t work.

How can I do so that when I click an option passes one value or another, not being links, if not javascript events (onClick) shows the element “modalHome” not be done.


#2

It sounds like you’re thinking that you can reference the modalHome element directly from Ajax? That’s not the case. You’d need to have a controller action that the Ajax calls to, and the view for that would in turn include the element.