Reputation: 215
I have an inline editor which saves the content using an AJAX function. This function calls my Yii controller where the data gets saved. This all works fine.
Now I shortened my urls using .htaccess
and Yii urlManager. When I call the controller to save data from my AJAX function I get a 301 response. If I copy the requested URL into my browser, everything works fine. Does anyone know why my post can't reach the controller?
AJAX function:
$.post("../inhoud/opslaan/id/" + id, {
dataType: "json",
data : editor.getData(),
success : alert('Opgeslagen!'),
} );
This url should work as well I guess, but gives the same response
"../index.php?r=inhoud/opslaan&id=" + id
.htaccess:
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
urlManager:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName' => false,
'rules'=>array(
'about' => 'site/page/view/about/',
'edit' => 'paginaitems/index/',
// default controller url setup
'<controller:w+>/<id:d+>'=>'<controller>/view',
'<controller:w+>/<action:w+>/<id:d+>'=>'<controller>/<action>',
'<controller:w+>/<action:w+>'=>'<controller>/<action>',
)
),
Controller action:
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
array('allow',
'actions'=>array('create','update','opslaan'),
'users'=>array('@'),
),
public function actionOpslaan($id)
{
$model=$this->loadModel($id);
$model->content = $_POST['data'];
$model->save();
}
Upvotes: 2
Views: 337
Reputation: 18402
Go into network debugger of your browser, check the Request-URL once your AJAX Request was triggered. -> here .. check your URL-Path.
1) I promise, your relative path near ../inhoud/opslaan/id/" + id
is not working fine. You should use absolute path's. There are many ways to handle absolut path's in an application. For example, in Yii you could add this to your layout HTML-Head:
<script type="text/javascript">
//node base url set global var "baseURL"
var baseURL = '<?php echo Yii::app()->request->getBaseUrl(true); ?>';
</script>
On this way you are able to build your request URL absolute:
<script type="text/javascript">
$.post(baseURL+"/inhoud/opslaan/id/" + id, {
dataType: "json",
data : editor.getData(),
success : alert('Opgeslagen!'),
});
</script>
2) Also check out "filters", "actions" & "accessRules" in your controller. If AJAX is blocked on Yii side, you need to make it work by configure your "filters" and stuff.
3) Check your urlManager-rules and make it as simple as it could by just putting in this rule:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName' => false,
'rules'=>array(
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
'/inhoud/opslaan/<id>' => array('inhoud/opslaan', 'urlSuffix' => '/', 'caseSensitive' => false),
),
),
Upvotes: 1