best practice: loading model from serialised date in javascript

Hi,

I wanted to ask what is your best way to load model from data send via ajax call using serialize javasctipt function. I do it like that:

view:




$('.save').click(function(){

		$.ajax({

			type :'POST',

			cache : false,

			url : '".Url::to(["test/test"])."',

			data:{form:$('.form').serialize()},

			success : function(data) {

			 // some actions

			}

		});

	});



controller:




parse_str(\Yii::$app->request->post("form"),$form);

		

$model = new MyModel;

$model->load($form);



Is there a better way?

Hi Andrzej,

I think you can use it by simpler way like below:


		

$model = new MyModel;

$model->attributes = \Yii::$app->request->post("form");



Take a look at documentation on Yii base model http://www.yiiframework.com/doc-2.0/yii-base-model.html#$attributes-detail.

Cheers,

Andrzej :)

Hi,


$model = new MyModel;

$model->attributes = \Yii::$app->request->post("form");

hmm, that doesn’t work, I think $model->attributes requires array while \Yii::$app->request->post(“form”) is string. That is why I used parse_str (or mb_parse_str). Maybe there is something I’m missing?

Thanks