2017-11-25 223 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

});