Custom form on submit or on click of save changes take me to home page of settings

Question

I have opened a submenu page called "My App Settings". There, I render the following form:

<div class="wrap">
  <h1>My App Settings</h1>
  <form id="form-my-app">
    <table class="form-table">
      <tbody>
        <tr>
          <th scope="row">API Key *</th>
          <td>
          <input id="my-app-api-key" name="my-app_api_key" type="text" value="<?php
            $my_app_options = get_option('my-app_options');
            echo isset($my_app_options['api_key']) ? $my_app_options['api_key'] : '';
          ?>">
          </td>
        </tr>
      </tbody>
    </table>
    <p class="submit">
      <input id="my-app-api-nonce" type="hidden" value="<?php echo wp_create_nonce('my-app_api_nonce'); ?>" />
      <div class="settings-cta">
        <button id="btn-submit-apikey" class="button button-primary" type="submit">Save Changes</button>
      </div>
    </p>
  </form>
</div>

It works fine, I can save the data and run the server function on the following events:

  • when the user presses the save button
  • when the user presses enter

Except that… it does not work when there is a notification showing up on the top of the settings page. I have no idea why. This is the event that I have registered using jQuery:

$(document).on('submit', '#form-my-app', submitForm);

function submitForm(e) {
  e.preventDefault();
   // rest of the code
}

In addition to that, I also have another event:

$(window).load(windowOnLoad);

function windowOnLoad() {
  const url = new URL(window.location.href);
  const token = url.searchParams.get('token');
  if (token) {
    document.getElementById('my-app-api-key').value = token;
    document.getElementById('btn-submit-apikey').click();
  }
}

The weird thing is that, when the problem occurs, I’m redirected to the General Settings page, and the URL is: [base-url]/wp-admin/options-general.php&my-app-api-key=[value]

Has anyone experienced this and knows how to fix?

0
Amanda Ferrari 2 years 2020-10-24T12:10:23-05:00 0 Answers 14 views 0

Leave an answer

Browse
Browse