这是一个jQuery脚本,我正在使用它将输入发布到数据库,假设提交数据的用户已登录,并且没有为用户提交数据的项目创建现有条目。
目前它没有产生任何结果,我也不完全清楚为什么,因为我不经常使用jQuery。
下面是一个流程图,说明了我正在努力实现的目标:
function csv_three_script() {
//Include Javascript library
wp_enqueue_script(
\'csv3\',
plugins_url(
\'/js/demo.js\',
__FILE__
),
array(
\'jquery\'
)
);
wp_localize_script(
\'csv3\',
\'MyAjax\', array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\')));
}
add_action( \'wp_enqueue_scripts\', \'csv_three_script\' );
function check_db(){
global $table;
global $quanid;
$hf_userid = get_current_user_id();
global $wpdb;
$wpdb->get_results( $wpdb->prepare("SELECT count( 1 ) FROM $table WHERE ItemID = \'$quanid\' AND user = \'$hf_userid\'", ARRAY_A));
}
add_action(\'wp_ajax_check_db\', \'check_db\');
function update_entry(){
global $quanid;
$price = isset($_POST[$quanid]);
$hf_userid = get_current_user_id();
global $table;
global $wpdb;
$wpdb->update( $wpdb->prepare( \'$table\',
array(
\'ItemID\' => \'$quanid\',
\'Price\' => $price,
\'user\' => $hf_userid)));
}
add_action(\'wp_ajax_update_entry\', \'update_entry\');
function post_entry(){
global $quanid;
$price = isset($_POST[$quanid]);
$hf_userid = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prepare(
\'$table\',
array(
\'ItemID\' => \'$quanid\',
\'Price\' => $price,
\'user\' => $hf_userid
),
array(
\'%d\', \'%d\', \'%d\'
)
));
die();
return true;
}
add_action(\'wp_ajax_post_entry\', \'post_entry\');
<小时>
jQuery(document).ready(function() {
var data = {
action: \'is_user_logged_in\'
};
jQuery.post(ajaxurl, data, function(response) {
if (response == \'yes\') {
// user is logged in
jQuery.ajax({
type: \'POST\',
url: MyAjax.ajaxurl,
data: {
"action": "check_db",
"user": user,
"ItemID": ItemID
},
function(data) {
if (data.exists) {
//existing entry found, update entry
function UpdateRecord(id) {
jQuery.ajax({
type: \'POST\',
url: MyAjax
.ajaxurl,
data: {
"action": "update_entry",
"ItemID": ItemID,
"Price": Price,
"user": user
},
success: function(
response
) {
alert
(
"Price successfully submitted."
);
}
});
}
} else {
//existing entry not found, create new entry
jQuery("#submit").click(
function() {
var name = jQuery(
"#ItemID").val();
jQuery.ajax({
type: \'POST\',
url: MyAjax
.ajaxurl,
data: {
"action": "post_entry",
"ItemID": ItemID,
"Price": Price,
"user": user
},
success: function(
response
) {
alert
(
"Price successfully submitted."
);
}
});
});
});
}
}, \'JSON\');
} else {
// user is not logged in
alert("You must be logged in to submit prices.");
}
}
});