การส่งแบบ POST
$(function(){ $("#save_type").click(function(){ path = '/it_wallet/category/updatetype?id='+$('#type_id').val(); $.ajax({ url: path, type:'POST', dataType:'json', data:{name:$('#type_title').val(),description:$('#type_description').val()}, success: function (data) { } }); });});
PHP
public function actionUpdate($id) { $extraData = Yii::$app->request->post(); $model = Category::findOne($id); $model->name = $extraData['name']; $model->type_id= $extraData['type_id']; $model->image_path= $extraData['image_path']; $model->description = $extraData['description']; $model->save(); echo json_encode(array("id"=>$model->id,'type_id'=>$model->type_id,"name"=>$model->name,"description"=>$model->description,"image_path"=>$model->image_path),JSON_PRETTY_PRINT); }
การส่งแบบ GET
$.ajax({ url: '/it_wallet/category/show_content', type:'GET', dataType:'json', success: function (data) { // alert("show content"); // alert(data.title); info_data = data.all; } });
PHP
public function actionShow_content() { $request = Yii::$app->request->post(); $types = Type::find()->all(); $type_array = []; foreach($types as $type){ $categories_array = []; foreach($type->getCategories()->orderBy("sequence ASC")->all() as $cat){ $categories = ["id"=>$cat->id,"type_id"=>$cat->type_id,"name"=>$cat->name,"description"=>$cat->description,"image_path"=>$cat->image_path]; array_push($categories_array,$categories); } $type_each = ["id"=>$type->id,"name"=>$type->name,"description"=>$type->description,"categories"=> $categories_array]; array_push($type_array,$type_each); } echo json_encode(array("all"=>$type_array),JSON_PRETTY_PRINT); }
การส่ง Association Array ผ่าน Ajax ใน jquery
function UpAndDown(obj){ var row = $(obj).parents(".tab-category:first"); alert($(row).attr('id')); if ($(obj).is(".up")) { row.insertBefore(row.prev()); } else { row.insertAfter(row.next()); } var all_row = $(obj).parents("li:first").find('.tab-category'); var order_array = []; for(vi =0;vi<all_row.length;vi++ ){ var order=new Object(); id= $(all_row[vi]).attr('id'); hid = id.toString().substr(4); order.sequence=vi; order.id=hid; order_array.push(order); } //update sequence $.ajax({ url: '/it_wallet/category/update_sequence', type:'POST', dataType:'json', data:{order:JSON.stringify(order_array)}, success: function (data) { //alert(data.status); } }); }
PHP
public function actionUpdate_sequence() { $request = Yii::$app->request->post(); $orders = json_decode($request['order'],true); foreach($orders as $order){ $model = Category::findOne($order['id']); $model->sequence = $order['sequence']; $model->save(); } echo json_encode(array('status'=>$request['order']),JSON_PRETTY_PRINT); }