2017-11-25 222 views
0

我想以检索这种数据列表的结果与CakePHP的3阿贾克斯选择列表

<?= $this->Form->select('notif_message', 
    [ 'oui' => 'oui', 'non' => 'non'], array('id' => 'notifmess')); ?> 
<?= $this->Form->hidden('notifmessage', ['value' => $notif_message]) ;?> 

的目标是当用户chosse值,Ajax调用这个控制器来完成

public function notifmessage() // mise à jour des paramètres de notifications 0 = non, 1 = oui 
{ 

    if ($this->request->is('ajax')) { 

    $notifmessage = $this->request->data('notifmessage'); 

    if($notifmessage == 'oui') 
    { 
     $new_notif_message = 'non'; 
    } 
    else 
    { 
     $new_notif_message = 'oui'; 
    } 

    $query = $this->Settings->query() 
         ->update() 
         ->set(['notif_message' => $new_notif_message]) 
         ->where(['user_id' => $this->Auth->user('username') ])        
         ->execute(); 

    $this->response->body($new_notif_message); 
    return $this->response; 

    } 
} 

,我想这样做在阿贾克斯这一呼吁没有重装,我有这个脚本

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.notif_message').change(function(){ 
     $.ajax({ 
      type: 'POST', 
      url: '/settings-notif_message', 
      data: 'select.notif_message' + val, 
      success: function(data) { 
       alert('ok'); 
      }, 
      error: function(data) { 
       alert('fail'); 
      } 
     }); 
    }); 
}); 
</script> 

他不工作,没有什么^ h追加,但我不知道为什么,我没有在日志中的任何消息,我不能没有指示调试什么不不行

感谢

+0

什么是您的select元素生成的值,因为这些值是您需要使用的值。 – jeff

回答

0

在YOUT的JavaScript,你应该使用$('#notifmess').change(…$('[notif_message]').change(…而不是$('.notif_message').change(…
在CakePHP中,select方法的第一个参数将用作select标签的名称属性。

更新: 在您的控制器中,您正在检索$_POST['notifmessage']的值,这是隐藏输入字段的名称。 要得到用户的选择,你既要在控制器使用$this->request->data('notif_message');,或设立Ajax请求与notifmessage发送数据,像这样:

$('[name="notif_message"]').change(function(){ 
    $.ajax({ 
     type: 'POST', 
     url: '/settings-notif_message', 
     data: {'notifmessage' : this.value}, 
     success: function(data) { 
      // To change selected value to the one got from the server 
      $('#notifmess').val(data); 

      alert('ok'); 
     }, 
     error: function(data) { 
      alert('fail'); 
     } 
    }); 
}); 

(凡在此情况下this指的是<选择>标签。)

+0

伟大的建议!,我有Ajax调用,但我的目标的其余部分无法正常工作:数据库中的更新是无效的,我希望'oui'或'非'保存在我的看法,我didn'在CakePHP 3找到文档如何把'选定'y默认 – christ57

+0

我总是有'oui',无论我选择我总是有'oui',控制器有错误我猜 – christ57

+0

@ christ57我已经更新详细说明参数namings的答案。 – dferenc

0

我很接近成功:我的Ajax调用工作,数据库更新工作,我需要探微“选定”的其他投入,我与这个jQuery代码

<script type="text/javascript"> 
$(document).ready(function() { 
$('#notifmess').change(function(){ 
    var id = $('#notifmess').val(); 
    $.ajax({ 
      type: 'POST', 
      url: '/instatux/settings-notif_message', 
      data: {'id' : id}, 
       success: function(data){ 
    $('#notifmess option[value="'+data.id+'"]').prop('selected', true); 

}, 
error: function(data) 
{ 
    alert('fail'); 
} 

    }); 
}); 
尝试0

});