为了账号安全,请及时绑定邮箱和手机立即绑定

在 PHP 中获取未选中的复选框值

在 PHP 中获取未选中的复选框值

PHP
守着星空守着你 2023-05-12 14:27:41
我创建了一个表单,允许用户选择他们想要接收的通知,然后将此信息存储到数据库中。我意识到目前用户可以接收大约 10 个选项/通知,因此为每个用户将 10 个选项保存到数据库中,将很快填满数据库。相反,我想让它只将他们不想接收的通知类型存储到数据库中。目前,jQuery 只发送选中复选框的值,不发送未选中复选框的值。有没有其他人有更好的解决方案,或者对我如何发送未检查的值有任何想法,或者可能将其创建为 unchecked = "off" 和 checked = "on"查询var data = $('#notificationsform').serializeArray();$.ajax({  type: "POST",  url: base_url + "/api/save_notification_preferences",  data: data,  dataType: 'json',  cache: false,  success: function (response) {    var data = response.data;    if (response.status == "success") {      console.log(data.message);      $('#successtxt').html(data.message);      $('#success-snack').addClass('snackbar-active');      setTimeout(function () {        $('#success-snack').removeClass('snackbar-active');      }, 1500)      $(".close-article").click();    } else {      $('#errortxt').html(data.message);      $('#error-snack').addClass('snackbar-active');    }  }});PHP$notifications = $this->input->post('notifications');$me = is_user_logged_in();$delete1 = "DELETE FROM `notificationssettings` WHERE  userID ='$me' ";$this->db->query($delete1);foreach ($this->input->post('notifications') as $key => $bg):  $insertnotifications['type'] = $bg;  $insertnotifications['userID'] = is_user_logged_in();  $this->db->insert("notificationssettings", $insertnotifications);endforeach;$data = [  'status' => 'success',  'data' => [    'message' => "Notification settings saved succesfully.",  ],];echo json_encode($data);exit();
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

未选中的复选框值根本不会发送到服务器。


然而,由于您知道可能的选项是什么,您可以让您的 PHP 后端知道可能的选项,然后可以将已知选项列表与通过 POST 请求传入的选项进行比较。


<?php


// ...


$POSSIBLE_NOTIFICATIONS = [

  'reviews',

  'feed',

  'follows',

  'updates',

  'invites',

  'events',

  'inviterequests',

  'invitestatus',

  'othersocial'

];


$notifications_opted_in = $this->input->post('notifications');

$notifications_opted_out = array_diff($POSSIBLE_NOTIFICATIONS, $notifications_opted_in);



查看完整回答
反对 回复 2023-05-12
  • 1 回答
  • 0 关注
  • 71 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信