我正在使用 WooCommerce 并添加了一个附加字段“location_gps”来收集位置(纬度、经度)添加了 ajax 调用来收集数据。现在我被困在将数据输入当前用户(user_meta)中。
在 funtions.php 中添加了这个
// AJAX - implementation
function add_myscript(){
wp_enqueue_script( 'my-ajax.js', get_bloginfo('template_directory') . "/scripts/my-ajax.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myscript' );
function myAjax(){
global $wpdb;
//get data from our ajax() call
$long = $_POST['long'];
$lat = $_POST['lat'];
$results = "<p>".$lat.", ".$long."</p>"; // this is how it supposed to land in the DB
if($wpdb->insert('location_gps',array(
'long'=>$long,
'lat'=>$lat,
))===FALSE){
echo "Error";
}
else {
echo "Successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
// create custom Ajax call for WordPress
add_action( 'wp_ajax_nopriv_myAjax', 'myAjax' );
add_action( 'wp_ajax_myAjax', 'myAjax' );
这里是JS部分..
jQuery(document).ready(function() {
jQuery("#save_loc_button").click(function(){
var long = jQuery("input#long").val();
var lat = jQuery("input#lat").val();
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: { "action": "myAjax", "lat": lat, "long": long },
beforeSend: function(){
jQuery("#test-div").html('processing...');
},
success: function(event, request, settings){
jQuery("#test-div").html('');
jQuery("#test-div").append(event);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});