Search code examples
javascriptajaxcakephponchangecakephp-3.7

What alternative for javascript onchange event listener in cakephp 3?


I'm having an issue using javascript onchange event listener in cakephp3.7. In fact I have a e-commerce web application built with cakephp3.7 running fine. Now I want to enhance the sales submission form in the website, by dynamically loading extra fields that sellers fill based on the category of products the seller chooses. That means, if the sellers chooses electronic from the category input field, then the electronic exta fields that were previously of style display:none in the CSS, will now be displayed. The electronic extra fields are as follow with id=elctronic:

<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>

Then if the product is about clothes for exemple, the electronic input fields will be hidden and the clothes extra fields will be displayed with id=clothe as bellow:

   <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 where the onchange event listener is used is as bellow, and the javascript function extraForm() should get called, but it doesn't and there is the issue:

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

And then in the layout for the method add() of ProductsController, I set the extraForm() function 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 = "bloc"
} else {
    s3.style.display = "bloc"
}
}
</script>

It's three days now since I can't figure out what I'm missing. Yesterday I searched through the net and there were people saying that event listener such as onchange, onclick and onselect event listeners are deprecated for cakephp 3 and I don't understand how. So how to achieve the dynamic load of extra input form triggered by selected option in cakephp3.7.

**

  • FIRST EDIT

**

Like I said in the comments, I simplified the question to make it understandable. The full context is that I have 2 standarts fields category and subcategory. When the user select a category, an AJAX fonction presentes to the user a list of subcategories to choose from. My AJAX is:

$(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 categorie 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 choose a category the list of subcategory fetched from database by AJAX appears well in this form input, and this is where the onchange is set to call the extraForm() function, but does not:

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

And After subcategory selected, the relevant extra form doesn't appear, but if I manually change display to bloc in CSS, it does show, which means that the javascript function isn't called onchange event, I even used onselect but still not having it. And the javascript function extraForm is actually receiving 2 arguments like extraForm(s1, s2). This is my real context.

I'm really stuck here. Any help is really appreciated, thanks in advance.

- EDIT ACCORDING TO GREG'S REQUEST: According to Greg's comment this is my cake code to generate the list inside subcategory. I didn't know all these details were necessary since I thought it was cakephp 3 issues regarding javascript events 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();
            }
        }

Thanks in advance, best regards !


Solution

  • It's always very daunting not knowing what the real problem is, since this is not my first foray in using ajax along with cakephp. I can attest on Greg Schmidth great experience when he said "the subcategories won't display at all". In fact, 2 days later and when endeavouring to hunt down the real issue,

    • I emptied cache,
    • I removed browser cookies

    And suddenly the whole app started behaving unexpectedly,

    • The subcategories were not displaying any more

    • The jQuery based animations codes I made for animating advertisements on the website frontend were also getting weird.

    These all made me think of jQuery issue, and indeed it was the real issue. I'm using 3 differents versions of jQuery and all 3 versions are necessary for my projects. The 3 jquery versions were silently conflicting and were not giving me any clue to troubleshoot what was going wrong. Now that I know it's a jquery issue, I used the jQuery noConflict approach described in this link

     <?= $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
    

    The description was not as straightforward as it seemed but other questions on stackoverflow also contributed to help me.

    Ultimately, It's not an issue about whether we can still use enchange event with cakephp version 3 form helper, but rather an issue about the right $ variable used by jquery in ajax code to get subcategories, it was not yielding.