Is there a substitute for the Javascript onchange event listener in CakePHP 3?

Having trouble with the javascript onchange event listener in cakephp3.7. I've got an e-commerce web app running smoothly on cakephp3.7. Now, I want to improve the sales submission form by dynamically loading extra fields based on the product category chosen by the seller. If the seller selects "electronic" from the category input field, then the electronic extra fields, which were previously hidden with CSS, will be displayed. The electronic extra fields with id=elctronic include:

<div id="electronic">
<?php echo $this->Form->control('subcategorie',['label'=>'choose sub category', 'class'=>'form-control', 'option'=>['Computer','Phone','Multimedia'],'empty'=>'choose'); ?>
<?php echo $this->Form->control('brand',['class'=>'form-control', 'placeholder'=>'the brand']); ?>
<?php echo $this->Form->control('model',['class'=>'form-control', 'placeholder'=>'the model']); ?>
</div>

On the other hand, if the product is related to "clothes", the electronic input fields will be hidden and the clothes extra fields will be displayed with id=clothe as follows:

<div id="clothe">
<?php echo $this->Form->control('Gender',['label'=>'What gender?', 'class'=>'form-control', 'option'=>['Males','Females'],'empty'=>'choose'); ?>
<?php echo $this->Form->control('Size',['class'=>'form-control', 'placeholder'=>'Size']); ?>
<?php echo $this->Form->control('model',['class'=>'form-control', 'placeholder'=>'the model']); ?>
</div>

The category input field implements the onchange event listener which should trigger the javascript function extraForm(), but it's not working as expected:

<?php echo $this->Form->control('category',['id'=>'categ','label'=>'choose category', 'class'=>'form-control', 'options'=>['electronics','clothes'],'empty'=>'choose'),'onchange'=>'extraForm("categ"); ?>

Furthermore, in the layout for the method add() of ProductsController, the extraForm() function is defined as below:

<script>
function extraForm(s1){
 var s1=documentgetElementById(s1);
 var s2=documentgetElementById("electronics");
 var s3=documentgetElementById("clothes");
  if(s1.value == "electronics"){
    s2.style.display = "block"
} else {
    s3.style.display = "block"
}
}
</script>

After researching without success, it seems that using event listeners like onchange, onclick, and onselect are deprecated for cakephp 3. How can I accomplish the dynamic loading of extra input forms triggered by selected options in cakephp3.7?

**

  • FIRST EDIT

**

To simplify the question, I have 2 standard fields: category and subcategory. When a user selects a category, an AJAX function displays a list of available subcategories. Here is the AJAX code:

$(document).ready(function(){

$('#getSubCat').change(function(e){

    $.ajax({
        type: "POST",
        url:  "/products/getsubsaterogie",
        data: {categ: $(this).find('option:selected').text()},
        dataType: 'json',
        cache: false,
        headers : {
            'X-CSRF-Token': $('[name="_csrfToken"]').val()
        },
        success: function(data){
            console.log(data);
            let subcat = $('#subcategories')

            for (let sc of data) {
                console.log(sc.subcategorie)
                $('<option />', {value: sc.subcategorie_id, text: sc.subcategorie}).appendTo(subcat);
            }
        }
    });

    e.preventDefault();
})

}) The category input field is:

  <?php echo $this->Form->control('categorie_id', ['id'=>'getSubCat', 'options' => $categories, 'label' => __("What category ?"), 'class'=>'form-control', 'empty' => '(choose)']); 
                                               ?>

After the user chooses a category, the list of subcategories fetched by AJAX appears correctly in this input field. The onchange event is set to call the extraForm() function, but it doesn't trigger:

 <?php echo $this->Form->control('subcategorie_id', ['id'=>'subcategories', 'label' => __("What subcategory ?"), 'class'=>'form-control', 'options'=> [],'empty' => '', 'onchange' => 'myFormShow("getSubCat","subcategories")']); 
                                               ?>

Even after selecting a subcategory, the relevant extra form doesn't appear. Manually changing the display to block in CSS shows it, indicating that the javascript function isn't being called on the onchange event. I've also tried using onselect without success. The extraForm() function actually receives 2 arguments like extraForm(s1, s2). Any help is greatly appreciated.

- EDIT ACCORDING TO GREG'S REQUEST: Upon Greg's comment, this is the cake code to generate the list of subcategories. I didn't realize these details were necessary, as I believed it was a cakephp 3 issue related to javascript event listeners.

public function getsubsaterogie(){
            if($this->request->is('ajax')){
                $d = $this->request->getData();
                $subcat = '';
                $cat = TableRegistry::get('Categories')->find()
                ->where(['categorie' => $d['categ']])
                ->select('id')
                ->first();

                if(!empty($cat)){
                    $subcat = TableRegistry::get('Subcategories')->find()
                    ->where(['categorie_id' => $cat->id])
                    ->all();
                }

                echo json_encode($subcat);
                exit();
            }
        }

Any assistance is highly appreciated. Thank you.

Answer №1

It can be quite intimidating not knowing the root cause of a problem, especially when dealing with ajax and cakephp for the first time. The statement made by Greg Schmidth about the subcategories not displaying resonated with me. Two days later, after trying various troubleshooting steps such as clearing cache and cookies, the application started acting strangely.

  • I cleared the cache
  • I deleted browser cookies

Suddenly, the subcategories stopped displaying and the jQuery animations for advertisements on the website frontend started behaving oddly.

  • The subcategories were no longer visible

  • The jQuery animations were malfunctioning

All signs pointed to a jQuery issue, and indeed, that was the actual problem. I had three different versions of jQuery in use, each essential for different aspects of my projects. These versions were conflicting silently, making it difficult to pinpoint the issue. Realizing it was a jQuery conflict, I implemented the jQuery noConflict approach as described in this resource.

 <?= $this->Html- >script('http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js') ?>
    <?= $this->Html->script('lecker/ajax/getSubCategorie.js') ?>
    <script>
        var jQuery_1_12 = $.noConflict(true);
    </script>
<?= $this->Html->script('https://code.jquery.com/ui/1.12.1/jquery-ui.js') ?>
// This for the second jquery version

Although the solution was not as straightforward as anticipated, valuable insights from other queries on stackoverflow aided in resolving the issue.

Ultimately, the challenge wasn't about the compatibility of the enchange event with the cakephp version 3 form helper, but rather ensuring the correct $ variable was utilized in the jQuery ajax code to retrieve subcategories.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS: ng-show causing flickering issue upon page refresh

Recently, I encountered an issue with my code snippet: <body> <ng-view></ng-view> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <script src="http://ajax.googleapis.com/ajax/ ...

Retrieve a file using AJAX in C# .NET MVC

I've been attempting to utilize the code below for downloading a file using Ajax in C# .NET MVC. However, it doesn't seem to be working as expected. Any insights on what might be causing the issue? I'm hoping that upon calling the downloadF ...

Changing ajax to cURL

I have been attempting to establish a connection with an API using cURL. Interestingly, when I opt for ajax, it functions properly; however, when I endeavor to utilize guzzleHTTP in Laravel or simple cURL, I encounter a "403 forbidden" error. Below is the ...

What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below: [ { "symbol": { "tickerSymbol": "@CH20", "vendor": "DTN", "marketName ...

Trouble with storing data in Angular Reactive Form

During my work on a project involving reactive forms, I encountered an issue with form submission. I had implemented a 'Submit' button that should submit the form upon clicking. Additionally, there was an anchor tag that, when clicked, added new ...

Avoid Scroll Below Stuck Navigation

I've been searching for a solution to my issue for some time now, and while I've come across many articles discussing similar problems, none of them seem to address my specific problem. In my React app, I have a mobile version where users can ta ...

Ways to retrieve a specific value in an array of objects

When working with the p5 javascript library, there is a convenient built-in function called {key} that captures the key you press. For instance, using text(${key},200,200) will display the key pressed at position 200, 200 on the canvas. If I were to stor ...

What is the reason for both the d3 line chart and bar chart being shown simultaneously?

On my website, I have implemented both a d3 bar chart and a line chart. You can view examples of them here: line_chart and bar_chart. However, in certain situations only one of the charts is displaying instead of both. Can anyone provide guidance on how ...

Using the jQuery plugin multiple times within one website

I have a decent understanding of jQuery and I'm in the process of developing a plugin. Specifically, it's a dropdown element that I'm working on. Everything functions correctly when there's only one dropdown on the site. However, when ...

Pictures acting erratic following the implementation of two setTimeout functions

I encountered an issue while developing a pong game using html/css/javascript. Everything was going smoothly until I introduced a second setTimeout() function. Here is the snippet of my html code: <!DOCTYPE html> <html> <head> <scrip ...

ajax clock encounters net::ERR_INSUFFICIENT_RESOURCES error

I recently set up an ajax php clock, but I keep encountering numerous net::ERR_INSUFFICIENT_RESOURCES errors in my console. Can anyone shed some light on why this might be happening? Below is the code responsible for calling out the clock function: $(docu ...

Configuring Braintree Client with JS v3 - encountering a null payment_method_nonce causing issues with form submission

I have successfully integrated Braintree into my Laravel 5.2 app using JS v2 client setup, but now I want to upgrade to v3. I have customized the code from the docs as follows: <form id="checkout-form" action="/checkout" method="post"> <div id= ...

Importing a 3D Model Using Three.js

I've been trying to import a 3D model by following tutorials. I managed to successfully import using A-Frame Tags, but encountering issues with Three.js. The code snippets are from a tutorial on YouTube that I referred to: https://www.youtube.com/watc ...

Creating a sidebar with child elements in Vitepress: A beginner's guide

I'm having trouble displaying my folder tree in the sidebar. When I click on a parent element like Group, the children elements are not showing up as expected. https://i.sstatic.net/kdc98.png One strange thing is that the Group elements do not have ...

How can you retrieve the X.509 Certificate from a P12 file using Node JS?

I obtained a p12 file that contains an X.509 Certificate. To handle this file, I am utilizing the forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'b ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

JavaScript code: "Retrieve the div element and append metadata to the HTML file

Currently, I am utilizing the subsequent technique to save a target tag on my webpage as an HTML file. function retrieveHtml(filename, elId, format) { var htmlEl = document.getElementById(elId).innerHTML; if (navigator.msSaveBlob) { // IE 10+ ...

What steps should I take to display a Modal upon a successful Oauth2 redirect?

I am currently working on an older web application that utilizes the portal/portlet architecture. Within the application, I have a feature that loads in a modal when accessed. The modal includes navigation functionality that allows customers to navigate t ...

In React Native, what is the method for utilizing index.js rather than separate index.ios.js and index.android.js files to create a cross-platform app?

Thank you for the help so far, I am new to React Native, and I'm trying to develop a cross-platform app. Here is my index.js file: import React from 'react'; { Component, View, Text, } from 'react-nativ ...

I am currently studying JavaScript. The syntax of my if statement with && appears to be accurate, however

I'm having trouble with the logic in my "Code your Own Adventure" program on Code Academy. I expect it to display "Great, come get your pizza!" when I enter PIZZA, YES, and YES as prompts, but instead it says "NO pizza for you!" I've tried using ...