我不想提交表单但我想获取输入字段的值并通过ajax将其发送到控制器以保存在数据库中。 我有以下JS代码,以帮助我获取输入字段的内容,并在用户输入3秒后发送到服务器端
<?php
$script = <<< JS
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var \$TitleInput = $('#product-product_title');
//on keyup, start the countdown
\$TitleInput.on('keyup input change paste',function(){
clearTimeout(typingTimer);
if (\$TitleInput.val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: data,
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});
JS;
$this->registerJs($script);
?>
在我的控制器中我有这个
public function actionCreate()
{
$model = new Draft();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \time();
if($model->save()){
echo draftId;
}else{
echo '0';
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
如果标题草稿成功保存,我想回复draftid 如何使这项工作得到任何帮助
以下是我的观点
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'enableClientValidation' => true,
'fieldConfig' => ['template' => '{label}{input}{hint}']
]); ?>
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'product_title')->textInput([
'class' => 'title-input',
'placeholder' => 'Give us a title for your items(include size,brand,color,material. e.t.c)',
])->label(false) ?>
</div>
<div class="col-md-12 text-muted">E.g Men's blue addidas glide running shoes size 11 </div>
</div>
<?= $form->field($model, 'user_id')->textInput() ?>
<?= $form->field($model, 'product_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'category_id')->textInput() ?>
我在我的视图中有这个但我想只保存用户输入值3秒后第一个输入字段的值
答案 0 :(得分:0)
尝试使用此JS,但在ID表单上更改$('#form')
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var $form = $('#form');
//on keyup, start the countdown
$form.find('input[type="text"]').on('keyup input change paste',function(){
clearTimeout(typingTimer);
if ($(this).val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: $form.serialize(),
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});