Hi guys,
I am working on a personal project right now using yii and was hoping somebody here could help me with something that has gotten me stuck.
Right now I have a form that a user fills out, I send it to the controller for validation and the controller decides what view to direct the user too.
What I would like to do is have ajax forward the data for validation, if valid I want to do some table updates and then having finished that I want to load the next view.
What method can you guys recommend for me to use to get the functionality I am looking for? I have tried calling $this->render from the Ajax function, but that does not work.
Cheers
You can do something like this.
In action:
if ($record->load($_POST) && $record->save()) {
Yii::$app->response->format = 'json';
return [
'record' => $record->toArray(),
'redirect' => '/url/to/redirect',
];
}
return $this->renderAjax('_edit', [
'record' => $record,
]);
In your view you can do something like
$.post(
$form.attr('action'),
$form.serialize()
)
.done(function(result) {
if (typeof(result) === "string") {
// replace form with result
} else {
// json returned
if (result.redirect) {
// do some stuff before redirecting,
// for example, close modal
window.location = result.redirect;
};
}
});
Obviously this example code cannot be used as is and needs to be rewritten according to your needs.
Thanks a lot! Got it to work