Yii2 Ajax .post to controller from dropdownList of view and some action upon receiving data

14,072

Solution 1

well I am sure you have a javascript error. You should actually have a lot of them too.

You are doing this

'onchange' => '$.post(Yii::$app->urlManager->createUrl . "users/A_action"), function(data) {
            $("#test_div").html(data)
        }'

You are not actually calling Yii::$app->urlManager->createUrl you are just using it as a string.

You probably need something like

...
['onchange' => '$.post("'.Yii::$app->urlManager->createUrl(["users/A_action"]).'", function( data ) {
      $("#test_div").html( data );
     })']);

Solution 2

Simple add a JS block, it is much more clean:

<?php $this->registerJs("
    jQuery(function($){
        $('select[name=Adrop]').on('change', function(){
             $.post(Yii::$app->urlManager->createUrl . 'users/A_action'), 
             function(data) {
                   $('#test_div').html(data)
             }
        });
    });");?>
Share:
14,072
David
Author by

David

Updated on July 12, 2022

Comments

  • David
    David almost 2 years

    I have a DropDown list. I've written the code but it's not working. Please help me to fix it:

    echo $form->field($model, 'Adrop')->dropDownList(
        [
            '' => 'Please Choose',
            '1' => 'item 1',
            '2' => 'item 2'
        ],
        [
            'onchange' => '$.post(Yii::$app->urlManager->createUrl . "users/A_action"), function(data) {
                $("#test_div").html(data)
            }'
        ]
    );
    

    Also I want to send selected data, and don't know where to write it.

    In the Controller I have this action

     public function actionA_action() {
         $data = "TTT";
         return $data;
     }
    

    Now when I select something in the DropDown list, nothing happens in my test_div :(

    UPDATE Thanks to Mihai P. now I'm using this code

    <?php
          echo   $form->field($model, 'Adrop')->dropDownList(
              [''=>'Please Choose','1'=>'item 1','2'=>'item 2'],
              [
              'onchange'=>'$.post( "'.Yii::$app->urlManager->createUrl(["users/A_action"]).'",function(data){
                    $("#test_div").html( data )
                    }']);
            ?>
    

    The HTML is formed in the following way

    <select id="A-adrop" class="form-control" name="A[Adrop]" onchange="$.post( &quot;/users/A_action&quot;,function(){
                    $(&quot;#test_div&quot;).html( data )
                    }">
    <option value="">Please Choose</option>
    <option value="1">item 1</option>
    <option value="2">item 2</option>
    </select>
    

    But when I choose something in debug this string is highlighted

     <option value="2">item 2</option>
    

    and there is one error saying

    Uncaught SyntaxError: Unexpected token }
    

    Final UPDATE

    I've added one closing bracket on the last string of this code there are two of them closing now as you can see, and that was the problem. Semicolumn also will be a plus, but I've tested code works without it OK. problem was in closing bracket.

     'onchange'=>'$.post( "'.Yii::$app->urlManager->createUrl(["users/A_action"]).'",function(data){
                        $("#test_div").html( data );
                        })']);
    
  • David
    David over 9 years
    Still nothing happens, but I tried to check errors, I've opened debuger of chrome and when I selected something in dropdown an error arrived. "Uncaught SyntaxError: Unexpected token } " and in code the following string was highlighted -> <option value="2">item 2</option>
  • topher
    topher over 9 years
    @David Looks like you missed the semicolon to close the statement.
  • David
    David over 9 years
    I've rechecked the code and we both missed closing brackets at the end! I'll Mark it in my question, and also will edit Mihai's answer. Thanks Guys!
  • David
    David over 9 years
    By the way what's better ? to write javascrpit/jquery inside yii's DropDownList or write all jquery code in a separate file registered to this view ? I have other jquery things going on there so I attached file anyway. What do you think ?
  • Mihai P.
    Mihai P. over 9 years
    writing it inside the dropdown is the worst solution. You can also registerJS into that file, this one is slightly better. To write the code into an external JS is even better. The best would be to add a css class to the dropdown and make JS that you can reuse in other views to based on that class. Yii for example has created data-confirm that can be applied to any link and it shows a confirmation dialog. They can reuse it all over. A similar solution would be the best.
  • Rich Harding
    Rich Harding almost 6 years
    Thank you for the answer, which put me on the right path to solving an issue I had. Just a note that it's quite difficult to use as above if you need to pass the value of the drop-down to the action. I got around this by using createUrl to tell me the correct one and then hard-wiring it. 'onchange' => '$.post("/pathto/controller/action?id="+$(this).val(), function( data ) { $("#form-element").html( data ); })