OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

400 (Bad Request) when calling the Ajax wp-admin/admin-ajax.php

  • Thread starter Thread starter Hussein Al-Mosawi
  • Start date Start date
H

Hussein Al-Mosawi

Guest
I checked all the similiar question but to no avail. Even chatGPt can't help now! Anyways, I'm using plain JavaScript to do a POST request to the WordPress backend so that I can work on the data.

This is my php code for creating the AJAX URL and the nonce.

Code:
 wp_localize_script('formalizer-js', 'formalizer_ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('formalizer_nonce'), 
    ));

This is my function that's supposed to retrieve the data in the backend:

Code:
function formalizer_save_settings() {
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log incoming request to debug
error_log('Incoming request: ' . print_r($_POST, true));

// Check nonce for security
if (!check_ajax_referer('formalizer_nonce', 'security', false)) {
    wp_send_json_error(array('message' => 'Invalid nonce.'));
    wp_die();
}

// Retrieve and process data from AJAX request
$data = isset($_POST['data']) ? json_decode(stripslashes($_POST['data']), true) : array();

// Log the processed data
error_log('Processed data: ' . print_r($data, true));

// Example: Save data to the database or perform actions
// For demonstration, log received data to error log
error_log('Received data: ' . print_r($data, true));

// Example response (adjust as per your needs)
$response = array(
    'success' => true,
    'message' => 'Settings saved successfully.',
    'data' => $data,  // Optionally send back processed data
);

// Send JSON response
wp_send_json_success($response);
wp_die();  // Always include wp_die() after sending JSON response
}
add_action('wp_ajax_formalizer_save_settings', 'formalizer_save_settings');
add_action('wp_ajax_nopriv_formalizer_save_settings', 'formalizer_save_settings');

And this is my js:

Code:
const data = {
      servicesLabels,
      productsLabels,
      servicesInputs,
      productsInputs,
    };

    try {
      const response = await fetch(formalizer_ajax_object.ajax_url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          security: formalizer_ajax_object.nonce,
          action: "formalizer_save_settings",
          data: data,
        }),
      });

      const result = await response.json();

      if (result.success) {
        console.log(result);
        alert("Settings saved successfully.");
      } else {
        console.log(result);
        throw new Error(result.data);
      }
    } catch (error) {
      console.error("Error:", error);
      //alert("An error occurred while saving settings: " + error.message);
    }

Am I doing something wrong with the actions? Nonce? Keep in mind the ajax URL is correct

<p>I checked all the similiar question but to no avail. Even chatGPt can't help now!
Anyways,
I'm using plain <code>JavaScript</code> to do a <code>POST</code> request to the <code>WordPress</code> backend so that I can work on the data.</p>
<p>This is my <code>php</code> code for creating the <code>AJAX</code> URL and the nonce.</p>
<pre class="lang-php prettyprint-override"><code>
wp_localize_script('formalizer-js', 'formalizer_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('formalizer_nonce'),
));
</code></pre>
<p>This is my function that's supposed to retrieve the data in the backend:</p>
<pre class="lang-php prettyprint-override"><code>function formalizer_save_settings() {
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log incoming request to debug
error_log('Incoming request: ' . print_r($_POST, true));

// Check nonce for security
if (!check_ajax_referer('formalizer_nonce', 'security', false)) {
wp_send_json_error(array('message' => 'Invalid nonce.'));
wp_die();
}

// Retrieve and process data from AJAX request
$data = isset($_POST['data']) ? json_decode(stripslashes($_POST['data']), true) : array();

// Log the processed data
error_log('Processed data: ' . print_r($data, true));

// Example: Save data to the database or perform actions
// For demonstration, log received data to error log
error_log('Received data: ' . print_r($data, true));

// Example response (adjust as per your needs)
$response = array(
'success' => true,
'message' => 'Settings saved successfully.',
'data' => $data, // Optionally send back processed data
);

// Send JSON response
wp_send_json_success($response);
wp_die(); // Always include wp_die() after sending JSON response
}
add_action('wp_ajax_formalizer_save_settings', 'formalizer_save_settings');
add_action('wp_ajax_nopriv_formalizer_save_settings', 'formalizer_save_settings');
</code></pre>
<p>And this is my js:</p>
<pre><code>
const data = {
servicesLabels,
productsLabels,
servicesInputs,
productsInputs,
};

try {
const response = await fetch(formalizer_ajax_object.ajax_url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
security: formalizer_ajax_object.nonce,
action: "formalizer_save_settings",
data: data,
}),
});

const result = await response.json();

if (result.success) {
console.log(result);
alert("Settings saved successfully.");
} else {
console.log(result);
throw new Error(result.data);
}
} catch (error) {
console.error("Error:", error);
//alert("An error occurred while saving settings: " + error.message);
}
</code></pre>
<p>Am I doing something wrong with the actions? Nonce?
Keep in mind the ajax URL is correct</p>
 
Top