jQuery Form Doesn't Post

I am using cakephp version 4. In my template, I have:
echo $this->Form->create($mealplan, [“type” =>“post”]);
echo $this->Form->button(__(‘Submit’), [‘id’=>‘myId’]);
echo this->Form->end(); ?> <script type="text/javascript"> (’#myId’).click(function(event) {
$.post("/mealplans/edit", ({ data: selectedBoxes, userId: userId, total: total}), function(data, status) {
alert(“test 2”);

The post request never executes. The second alert button never pops up, just the first one does. I’ve also tried:

<script  type="text/javascript">
$('#myId').click(function(event) {
$.post("/mealplans/edit", function(data, status) {		
alert("test 2");

data, selectedBoxes, userId, and total are set in the script that precedes this snippet.


   $(document).ready(function() {

    You may need:

preventDefault();  you could probably look up usage.

Hijacking the submit button I would think is bad practice. It will confuse, and you cannot rely on every browser to behave the same with it - it may well execute your JS and also submit the post, or just one or the other. Try instead if creating a button outside of the form and associate your click to that.

How is the button going to send the form data if it’s outside of the form?

I tried adding another button but now not even the click event works. Also I placeed an alert at the top of the javascript code that I’m linking to and it never popped up. The following never executes:

 $(function() {

Because your JavaScript is doing a Post command. All this is automatic within a form, as it was back in the '90’s! You don’t need any JavaScript to post when the submit input button is within the form.

For your scripts etc., maybe show the whole file here if possible. As a disclaimer though I won’t be providing code solutions until you consider the decision I put before you here: Passing Variable to the Method - #15 by Jawfin

A good starting point for jquery could be here:

Jquery Get/Post can be found here:

And on Youtube, there is a Tutorial from Alison Pito (he also covers many more questions about cake4 and also has many tutorials for cake3 which can help)

I tried using the document ready function as suggested by jimgwhit as well but it still didn’t work.

Thank you for the links, dirk

It’s working now with the following code:

  $.get("/mealplans/edit/", ({ data: selectedBoxes, userId: userId, total: total}), function(data, status){
    alert("total " + total);

However the data named total isn’t getting sent over the url. A bunch of data that I don’t care about is getting sent over the url.

How should anyone know, where „data named total“ is defined or collected in your script or what „a bunch of data, that i dont care about“ means?

It is nearly impossible to help you, if you only supply pieces of code, that you copied and pasted without understanding what you are doing.
Sorry to say, but you should start right from the beginning, go through the tutorial at cakephp and before that you should invest some time to understand the basics of software development and logical structures.
Please excuse my bad english and the hard words, but you are doing yourself no favour.

$.get("/mealplans/edit/", ({ data: selectedBoxes, userId: userId, total: total}), function(data, status){

The total is in the data parameter in the code snippet above. I can’t get the total sent to the response page like I can get the query parameters. I want to read the total on the submitted page like I can the form inputs.

So I want to use something like $_REQUEST[‘total’] in the response page but it only returns total in the javascript not the php.

I’m trying to use the following to get the total:

	$json = file_get_contents('php://input');
	$data = json_decode($json);	
	echo "total " . $data->total;

But the following returns an empty string which I think is because it comes from a redirect:

echo "test " . file_get_contents('php://input');

It was returning an empty string because I didn’t have an action tag in my form. Now when I use the code below, it dumps the form inputs but not the json data from the jQuery post.
$json = file_get_contents(‘php://input’);

please show the code of the whole form

<?php echo $this->Form->create($mealplan, ['url' => ['action' => 'edit']]);

<div id="draggables_box">

<p>Click to show the tiles and then click again to hide them. Drag the tiles to the right side to create your menu. </p>
<div style="float:right; margin-right: 6px;"><a href="javascript:location.reload(true)">RESET</a></div>	

<table style="border: none" width="100%">

<?php for ($i = 1; $i <= 4; $i++) {

echo "<td><div id='clickMe" . $i .  "' class='tile_button'>" . $i . "00 cal tiles</div></td>";

<?php for ($i = 5; $i <= 8; $i++) {
echo "<td><div id='clickMe" . $i .  "' class='tile_button'>" . $i . "00 cal tiles</div></td>";

<?php for ($i = 1; $i <= 8; $i++) {
echo "<div id='showMe" . $i .  "' style='display: none'>";

foreach ($tiles as $tile):
if ($user_id ==  $tile->user_id){
if ( $i == $tile->cat_id ) {
<!-- begin of draggable div-->
<div id="draggable<?php echo $tile->id; ?>" class="draggable_meal draggable ui-widget-content item">
<div class="calorie_icon"> <?= $tile->cals_per_serving; ?> CALS</div>

<span><?php echo $tile->short_description; ?></span>

echo $this->Form->hidden('cals_per_serving'. $tile->id, [
    'id' => 'cals_per_serving'. $tile->id,
	'multiple' => 'true',
	'name' => 'cals_per_serving',
    'value' => $tile->cals_per_serving,


</div><!-- end of draggable div-->
} //end if
} //end if
</div><!-- end of showMe div-->
} //end for

<br style="clear: both;" />
</div><!-- end div for draggables_box -->

<!--div id="droppable_box" class="rightSide"-->
<div id="droppable_box" class="ui-widget-header">
<b>Total Calories:&nbsp;&nbsp;<div name="response" id="response"></div></b>

<p>Drag the meal tiles over here.</p>

</div><!--end div for droppable_box -->

<br style="clear: both;" />

echo $this->Form->button('Submit Mealplan', ['type' => 'submit', 'class'=>'submit-btn', 'id'=>'myId']);
echo $this->Form->end(); 

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  $( function() {		
var i;
for (i = 0; i < 77; i++) {

    $( "#draggable"+i ).draggable();
    $( "#droppable_box" ).droppable({
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
  } );

<?= $this->Html->script(['get_total_calories'])?>

There might be some errant } tags because I deleted some of the code.

The get_total_calories.js script that it links to is as follows:

 $(function() {
	var selectedBoxes = new Array();
	var total = 0;	
	var userId = 1;
	for (var i=1;i<100;i++){
        $( "#draggable" + i ).draggable();
        drop: function(event, ui) {
		if($(ui.draggable).hasClass("rightSide"))//If already on the right do nothing
				return true;
			var data = $(ui.draggable).attr('id');


			for (var i=1;i<100;i++){
		    if(data == "draggable" + i){
			//The parseInt() function parses a string argument and returns an integer
			var myInt = parseInt($('#cals_per_serving' + i).val());

		if ( typeof myInt === 'undefined' || !myInt) {
		myInt = parseInt(0);
		total += parseFloat(myInt);

I am trying to get the jQuery variable in my PHP by using the following:
In my template:

    echo  $this->Form->create($mealplan);
    echo $this->Form->button('Another Button', ['type' => 'button','id'=>'myId2']);
    echo $this->Form->end();
    echo "test " . $_REQUEST['test'];// Undefined index: test
    print_r($_REQUEST); //Array ( )

In my script:

    $("#myId2").click(function() {
    $('#result').append('total:  ' + total);
    var test = $("#result").html();
        type : 'POST',
        url : "<?php echo Router::url(['controller' => 'mealplans', 'action' => 'add']); ?>",
        dataType : 'HTML',
        data : {
            test : test
        success : function(data) {

The ajax function returns confirmation of success but when I try to access the variable with $_REQUEST[‘test’], it returns the error: undefined index: test. I created this with help of the following forum post: