Yii2 Jui Sortable Ajax

Hi All,

I am experimenting with the yii2 sortable widget. I copied the example code from the yii2 guide and got it running pretty easily and have figured out how to pull data from a table to populate the list.

However, I am having trouble figuring out how to post a re-ordered list back to my controller using ajax. In the original yii, I used a snippet of code in ‘options’=>array() that looked like this:




'options'=>array(

                'update'=>"js:function(){

                        $.ajax({

                                type: 'POST',

                                url: '{$this->createUrl('controller/sort/uniqueId/$id/')}',

                                data: $(this).sortable('serialize'),

                        });

                }",

        ),




Does anybody have a snippet in Yii2 that they would be willing to share that will POST back to the controller via ajax?

Ok, so I’m getting a little closer. I’ll share what I have below, but there is one thing holding this up.

When I change the order of the sortable list, it looks like Yii2 is stripping the serialized data out of the post request, so my data is not getting to the controller.

Not sure how to proceed, any help or tips would be appreciated…





<?php 		

		$items = [];

		foreach ($query as $p) {

			$items[$p['id']] = [

				'content' => ''.$p['product'].'',

				'options' => ['tag' => 'li', 'class'=>'list-group-item','id'=>'item-'.$p['id']],

			];

		}

	        $url = Url::to(['mycontroller/view', 'subscriptionId' => $p['subscriptionId']]);


		echo Sortable::widget([

			'id'=>'sortable',

			'items' => $items,

			

						]);

						

$this->registerJs(

    "

	$(document).ready(function () {

    $('ul').sortable({

        axis: 'y',

        stop: function (event, ui) {

		var data = $(this).sortable('serialize');

		var url = '{$url}'

		$('h6').text(data);    // Checks to make sure that data is compiled correctly

		$('h5').text(url);     //  Checks to make sure url is compiled correctly

            $.ajax({

                type: 'post',

                data: data,

                url: url,

		contentType: 'application/json; charset=utf-8',

		dataType: 'json',

            });

			}

		});

	});

	"

);

	?>


		Query string: <h6></h6>

		Url: <h5></h5>