I'm creating a plugin where I have a dashboard that is done with Settings API
. I'm trying to save data from that form via AJAX
.
Form:
public function agy_dashboard_page() {
?>
<form id="agy-form-submit" action="options.php" method="post">
<?php
settings_errors( 'agy_settings_fields' );
wp_nonce_field( 'agy_dashboard_save', 'agy_form_save_name' ); // CHECK THIS AT THE END
settings_fields( 'agy_settings_fields' );
?>
<div id="agy-tab1" class="agy-tabcontent">
<?php do_settings_sections( 'agy_settings_section_tab1' ); ?>
</div>
<?php
submit_button(
__( 'Save Changes', 'agy' ),
'',
'agy_save_changes_btn',
true,
array( 'id' => 'agy-save-changes-btn' )
);
if ( wp_doing_ajax() ) {
wp_die();
}
?>
</form>
<?php
if ( ! isset( $_POST['agy_form_save_name'] ) ||
! wp_verify_nonce( $_POST['agy_form_save_name'], 'agy_dashboard_save' ) ) {
return;
}
?>
<?php
}
Register Settings:
public function agy_register_settings() {
register_setting( 'agy_settings_fields', 'agy_settings_fields', 'agy_sanitize_callback' );
// Adding sections
add_settings_section( 'agy_section_id', __( 'General', 'agy' ), array(
$this,
'agy_settings_section_callback'
), 'agy_settings_section_tab1' );
// General page fields
add_settings_field( 'agy_section_id_enabled_disabled', __( 'Enable / Disable', 'agy' ), array(
$this,
'agy_section_id_enabled_disabled'
), 'agy_settings_section_tab1', 'agy_section_id' );
add_settings_field( 'agy_section_id_unregister_user', __( 'Show for unregistered users only', 'agy' ), array(
$this,
'agy_section_id_unregister_user'
), 'agy_settings_section_tab1', 'agy_section_id' );
add_settings_field( 'agy_section_id_debug_mode', __( 'Activate Debug mode', 'agy' ), array(
$this,
'agy_section_id_debug_mode'
), 'agy_settings_section_tab1', 'agy_section_id' );
}
AJAX:
function agyAjaxSubmit() {
var agyFormData = new FormData(this);
agyFormData.append('agy_save_changes_btn', 1);
agyFormData.append('security', agy_public_ajax.agy_publisher_name);
$.ajax({
type: 'POST',
url: agy_admin_ajax.ajax_ajaxurl,
data: agyFormData,
processData: false,
contentType: false,
success: function () {
console.log('work');
},
error: function () {
console.log('not work');
}
});
return false;
}
$('#agy-form-submit').submit(agyAjaxSubmit);
Without AJAX
, it's working fine. But with AJAX
, it's not saving any data.
Any help is appreciated.