I'm struggling with this for a couple of days already, so any help is most welcome. Not my first time setting up Ajax with WP, so I have some idea at the least. It concerns a very standard form validation and inputting info to database. This all inside of a plugin.
So, what works: form submission works, the jquery script is activated and forwards the input info to the callback PHP file.
Problem is that, for some reason, the specific function that handles the form on that PHP file is not activated.
So, what do I have? I will skip the form as such because it seems pretty standard.
1 - the javascript/jquery
/plugins/alert-widget/submit_handler.js
jQuery(document).ready( function() {
jQuery("#alert_set_form").on("submit", function(e) {
e.preventDefault();
var info = jQuery("#alert_set_form").serialize();
// Post to the server
jQuery.ajax({
type:"POST",
url:ajaxAlert.ajaxurl,
data:info,
dataType:'json',
success: function(data){
jQuery("#alert_set_form .stm-validation-message").html(data);
}
});
});
});
1- the main PHP plugin file that builds the form and is supposed to handle the validation/data input.
/plugins/alert-widget/alert_widget.php
add_action('wp_ajax_bda_alert', 'bda_alert_validation');
add_action('wp_ajax_nopriv_bda_alert', 'bda_alert_validation');
/* this commented out code was placed just to check if call hits the file, which it does
if( isset($_POST['model'])){
$criteria = array(
'model' => $_POST['model'],
'body' => $_POST['body'],
'price' => $_POST['price'],
'mileage' => $_POST['mileage'],
'ca-year' => $_POST['ca-year'],
'fuel' => $_POST['fuel'],
'transmission' => $_POST['transmission']
);
$criteria = base64_encode(serialize($criteria));
$response = $criteria;
wp_send_json( $response );
wp_die();
}
*/
function bda_alert_validation(){
//does validation and input
$response =array(
'data' => 'success',
'supplemental' => array(
'message' => 'success',
),
) ;
wp_send_json( $response );
wp_die();
}
add_action('init', 'alert_form_init' );
function alert_form_init() {
wp_register_script( "alert_form_script", WP_PLUGIN_URL.'/alert-widget/submit_handler.js', array('jquery') );
wp_localize_script( 'alert_form_script', 'ajaxAlert', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'alert_form_script');
}
/wp-json
, look upregister_rest_route
, e.g. tomjn.com/2017/01/23/writing-wp-rest-api-endpoint-2-minutesaction
passed with your form data?