I am implementing a form that request a process with ajax to sync 2 databases and I need to wait until the process finish.
In my form I have the flowing code to send the db credentials:
<div class="col-lg-offset-1 col-lg-11">
<?=
Html::a('Sync Databases', ['runsync'], [
'class' => 'btn btn-primary',
'id' => 'ajax_link_02',
'data-on-done' => 'linkFormDone',
'data-form-id' => 'syncdb_form',]
)
?>
and I also register the js with the ajax
function handleAjaxLink(e) {
e.preventDefault();
var
$link = $(e.target),
callUrl = $link.attr('href'),
formId = $link.data('formId'),
onDone = $link.data('onDone'),
onFail = $link.data('onFail'),
onAlways = $link.data('onAlways'),
ajaxRequest;
$("#show_msg").html("Loading.... please wait...");
ajaxRequest = $.ajax({
type: "post",
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
// Assign done handler
if (typeof onDone === "string" && ajaxCallbacks.hasOwnProperty(onDone)) {
ajaxRequest.done(ajaxCallbacks[onDone]);
}
// Assign fail handler
if (typeof onFail === "string" && ajaxCallbacks.hasOwnProperty(onFail)) {
ajaxRequest.fail(ajaxCallbacks[onFail]);
}
// Assign always handler
if (typeof onAlways === "string" && ajaxCallbacks.hasOwnProperty(onAlways)) {
ajaxRequest.always(ajaxCallbacks[onAlways]);
}
}
var ajaxCallbacks = {
'linkFormDone': function (response) {
$('#show_msg').html(response.body);
}
}
The ajax call works fine and call the controller:
public function actionRunsync() {
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new \app\modules\admin\models\syncdb();
$response = $model->runSyncDb($_POST);
$res = array(
'body' => $response,
'success' => true,
);
return $res;
}
}
But is not waiting to the process
$model->runSyncDb($_POST)
to finish. If I comment the process and add a text it works fine but not if the process takes long.
What am I doing wrong?
I just added async false to the ajax request:
async: false,
so now the ajax is like this:
ajaxRequest = $.ajax({
type: "post",
async: false,
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
Not sure the best way but works perfectly...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.