当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Wordpress: Using OnClick() and Ajax to fire off a php function from a checkbox

问题描述:

I am attempting to use the onclick() function and Ajax from within a checkbox to write insert or update a record in a database.

The onclick() function properly calls the javascript code but the Ajax call never calls the PHP function to save the data.

Below is the code:

PHP:

This is the code for the checkbox:

<input type="checkbox" id="completed-'.$c.'" value = "' .$c. '" ' .$vcl_compcheck. ' ' .$vcl_compdisable. ' onclick="frontend_checklist_checkbox_changed(' .$c. ')">

Here is the rest of the PHP code:

add_action('wp_ajax_fc_checkbox_changed', array('Frontend_Checklist', 'changedAjax'));

public static function add_js() {

wp_enqueue_script('frontend-checklist', plugins_url('frontend-checklist.js', __FILE__), array('jquery'));

wp_localize_script( 'frontend-checklist', 'frontendChecklist',

array(

'ajaxurl' => admin_url( 'admin-ajax.php' ),

)

);

}

public static function changedAjax() {

$user_ID = get_current_user_id();

if ($user_ID == 0) die;

$ca = (int)$_POST('fc_itemID');

$fc_completed = "on";

$casql = $wpdb->prepare('SELECT completed from wp_fc_vendorlist WHERE fc_vendorID = ' .$user_ID. ' and fc_itemID = ' .$ca. ' ORDER BY fc_itemID ASC' );

$cachk = $wpdb->get_row($vsql, ARRAY_A);

$table_name = 'wp_fc_vendorlist';

if($cachk =='') {

$wpdb->query("INSERT INTO $table_name (fc_itemID, fc_vendorID, completed) VALUES ('$ca', '$user_ID', '$fc_completed')" );

} else {

$wpdb->query($wpdb->prepare("UPDATE $table_name SET completed= $fc_completed WHERE fc_vendorID=$userid and vc_itemID = $ca"));

}

output();

die;

}

and finally, this is the javascript code:

function frontend_checklist_checkbox_changed(fc_listID) {

var checkbox;

var fc_listID;

checkbox = jQuery('#completed-' + fc_listID);

if (checkbox && checkbox.prop('checked')) {

var data = { action: 'fc_checkbox_changed', fc_listID: fc_listID};

jQuery.post(frontendChecklist.ajaxurl, data);

alert("The javascript funciton has been initiated ");

}

}

the Alert box fires in the javascript code, so I know it is getting to that point, but it never goes beyond that into calling the changedAjax() function in PHP.

I know I'm missing something simple, I just can't figure out what.

Thanks in advance.

分享给朋友:
您可能感兴趣的文章:
随机阅读: