You will need a function that will handle the sent data from the form.
Then you have to attach this function to the wp_ajax_nopriv_[your_action_name]
hook.
function process_form() {
// process $_POST data, prepare $output to return
//
// send: array( 'success' => true, 'data' => $data )
wp_send_json_success( $data );
wp_die();
}
// add_action( 'wp_ajax_my_action', 'process_form' ); // ajax from back-end
add_action( 'wp_ajax_nopriv_my_action', 'process_form' ); // ajax from front-end
Add code in functions.php
or in plugin.
Now in the javascript code, you need to collect data from the form fields and add action field with the appropriate value.
It is also worth checking their correctness before sending.
Using ajax, send data to the server and display the result. Remove:
$(".submit").click(function () {
$("fieldset").hide();
$("#res-tab").show();
});
And add:
$("#idForm").submit(function(e) {
var form = $('#msform');
var url = ajax_object.ajax_url;
// var url = "<?php echo admin_url( 'admin-ajax.php' ); ?>", // if this is inline JS
var fdata = {};
fdata['action'] = 'my_action';
fdata['prodotto'] = form.find('input[name="prodotto"]').val();
// ... colect remaining data
$.ajax({
type: "POST",
url: url,
data: fdata,
success: function(resp)
{
var res_tab = $("#res-tab");
//
// show response "resp.data" from the php script.
res_tab.empty();
res_tab.append(resp.data);
$("fieldset").hide();
res_tab.show();
},
error: function(error) {
console.log(error);
},
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
If your javascript code is in separated file, add this to function.php
to localize script
wp_localize_script('script_name', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
));
If javascript is inline then add var url = "<?php echo admin_url( 'admin-ajax.php' ); ?>"
.
Replace my_action
in php and javascript with some names.
script_name
replace with the name under which the js file was registered.
Read about ajax in codex.
Edit
script registration:
function enqueue_radio() {
if ( is_page_template('modello-2.php' )) {
wp_enqueue_script( 'radio', get_stylesheet_directory_uri() . '/js/radio.js', array('jquery'), '', true );
wp_localize_script( 'radio', 'ajax_object',
array('ajax_url' => admin_url('admin-ajax.php')) );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_radio' );