The below code produces an error:
Notice: wp_enqueue_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the waitlist_update_call handle. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/food/domains/xyz.com/public_html/wp-includes/functions.php on line 5225"
It also shows an error in the console of:
POST https://theste.com/wp-admin/admin-ajax.php 400 (Bad Request)
PHP code in my functions file
wp_enqueue_script( 'update_call',
get_theme_file_uri( '/assets/js/update_call.js' ),
array('jquery'), null, true );
wp_localize_script('update_call', 'my_ajax',
array('ajax_url' => admin_url('admin-ajax.php')));
//calls Waitinglist data and creates table
add_action('wp_ajax_function_1', 'update_function'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'update'); // non logged in user can make a call
function update_function() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` =
'myupdate1' WHERE ID = '1'"));
die($results);
}
EDIT 1:
I was trying to call it directly. Please excuse my newness.Ok the fist below solved Enqueue issue but POST 400 error remains. The error is
POST https://x.com/wp-admin/admin-ajax.php 400 (Bad Request)
When clicking my button that is supposed to trigger I get -
Uncaught ReferenceError: update_functionis not defined
at HTMLButtonElement.onclick
I have changed my PHP in the functions file to:
function my_scripts() {
wp_enqueue_script( 'update_call', get_theme_file_uri( '/assets/js/update_call.js' ), array('jquery'), null, true );
wp_localize_script('update_call', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
//calls Waitinglist data and creates table
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action('wp_ajax_function_1', 'waitlist_update'); // logged in user can make a call
function waitlist_update() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'wp_wpdatatable_4' SET `currentstatus` =
'myupdate1' WHERE wdt_ID = '1'"));
die($results);
}
Seperate JS file is :
// JavaScript Document
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
action: 'waitlist_update',
success: function(data){
// callback function
}
});
and HTML is:
<button class="seat-btn" ID="update" onclick="update_function()">Go!</button>