【发布时间】:2015-02-04 00:42:18
【问题描述】:
自上次发布以来,所有代码均已更新。 我在编写这段代码时遇到了麻烦。这是给客户的。它应该做的是当用户以客户身份登录网站时。他们填写产品标准:年份、品牌、型号、选项 1。这会生成我的客户拥有的产品列表。他想要一个按钮来保存客户的标准,这样他们就可以在他们的用户部分单击它来提取产品,而无需再次进行搜索。
我在使用 ajax 和通过标准时遇到问题。所以在我的 js 文件中,这就是我的 ajax 函数:
function ajaxAddVehicleMeta(){
var userId = ''; // fill this in to somehow acquire the userID client-side...
var year = '<?php echo $year; ?>';
var make= '<?php echo $make; ?>';
var model= '<?php echo $model; ?>';
var option1= '<?php echo $option1; ?>';
var stdoropt= '<?php echo $stdoropt; ?>';
jQuery.ajax({
type: 'POST',
data: {
action: 'saveVeh',
userId: userId,
year:year,
make:make,
model:model,
option1:option1,
stdoropt:stdoropt },
url: comm_custom.ajaxurl, //this is the url found in functions
success: function(msg){
alert( "Data Saved: User ID " + userId + "." );
},
error: function(msg){
alert( "Data not saved: User ID " + userId + ".");
}
});
}
在我的functions.php文件中我有:
add_action( 'wp_ajax_saveVeh', 'saveVeh' );
add_action( 'wp_ajax_nopriv_saveVeh', 'saveVeh' );
function saveVeh(){
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$option1 = $_POST['option1'];
$stdoropt = $_POST['stdoropt'];
//if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
if(!$user_id):
echo 'failed, not logged in';
exit;
endif;
if($year){
$vehicle1 = $year.' '.$make.' '.$model.' '.$option1.' / '.$stdoropt;
}else if($_POST['width']){
$vehicle1 = $_POST['width']. ' ' .$_POST['height']. ' ' .$_POST['rim'];
}
update_user_meta( $user_id, '_vehicle1', $vehicle1);
//}
页面上有这个链接:更新
<a href="#" onclick="ajaxAddVehicleMeta()" class="vehicle-btn" >Save Search Criteria</a>
我发出警报,它告诉我它成功了。但它没有将它保存在用户元中。是不是我做错了什么?
comm_custom.ajaxurl 是 enqueue 脚本中的 admin-ajax.php 并对其进行本地化。
【问题讨论】:
-
data: { action: 'saveVeh', userId: userId }您没有在此处发布任何您正在获取的内容(php 中的 $_POST)。你也有 add_action 到 ajax_nopriv 的功能吗? -
我添加了 ajax_nopriv 操作。我必须在数据部分更改什么?
-
现在你只传递了 $_POST['userId'],所以你在 php 中的 post 值为 null。但这不是您的主要问题, is_logged in 必须返回 false 否则您将保存一个空的数据库条目。删除它进行测试。
-
我尝试添加 $_POST['tire-year'] 之类的,但我收到类似“userId:userId,tire-year:tire-year ...”的错误说它们是未定义的...我想在 onclick 的实际链接中添加更多内容吗?
-
你需要在传入之前设置变量。如果你只是想测试使用轮胎年:'轮胎年'等......实际上使用轮胎年代替
标签: php ajax wordpress variables