In a template file, I need to get the new data from the frontend when a user double-clicks and changes the record on a table. I tested and the console shows that the request is correct, however whatever I tried the admin-Ajax returns always Bad Request! The PHP code waiting for the request in the template file is:
add_action( "wp_ajax_update_records", "update_records" );
add_action( "wp_ajax_nopriv_please_login", "please_login" );
function update_records(){
global $wpdb;
$colName = "'" . $_POST['upd_column'] . "'";
$wpdb->update('Reservations',
array(
$colName => $_POST['upd_value']
),
array( 'ReservationID' => $_POST['record_id'] )
);
wp_die();
};
function please_login() {
echo "You must log in to work";
die();
}
The jQuery code sending the request is:
jQuery('#work td').dblclick(
function dolly_script() {
var text = jQuery(this).text();
var headerName = jQuery(this).attr('headers');
jQuery(this).text('');
jQuery('<input />').appendTo(jQuery(this)).val(text).select().blur(
function() {
var newVal = jQuery(this).val();
var selectionID = jQuery(this).closest("tr").children("td[headers='ReservationID']").text();
jQuery(this).parent().text(newVal).find('input').remove();
jQuery.ajax({
url: '../wp-admin/admin-ajax.php',
type: 'POST',
dataType : "json",
data: JSON.stringify({
action: 'update_records',
record_id: selectionID,
upd_column: headerName,
upd_value: newVal
})
})
})
});
I tried also without JSON.stringify and without datatype.
In functions file I have also added:
wp_register_script( 'dolly_script', '/wp-content/themes/bootcms/work.js');
$myAjax = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'dolly_script', 'ajax_url', $myAjax );
wp_enqueue_script( 'dolly_script' );
Inside the "add_action( 'wp_enqueue_scripts', 'myfunction' );" declaration.
If anyone could help is hugely appreciated, I spent a whole day but I found no solution.
I solved the problem. Here is the solution in case it helps others:
I moved the PHP function into the functions.php file.