Encountering a "400 Bad Request" error when using Ajax within WordPress

I've been trying to submit a form using Ajax within a plugin. I had two plugins, the first one was initially working but has stopped now and I can't seem to find any errors. I don't think the issue lies in the code itself, but I'm feeling a bit lost.

Here is my PHP:

wp_enqueue_script( 'b_form', plugin_dir_url( __FILE__ ) . 'js/b-form.js', array( 'jquery') );
wp_localize_script( 'b_form', 'ajax_url', admin_url( 'admin-ajax.php' ) );
include plugin_dir_path( __FILE__ ) . 'pages/b-form.php';

And here is my JS:

var fd = new FormData( document.getElementById( 'b_form' ) );
fd.append( 'action', 'b_generate_comparison' );
$.ajax({
     type: "POST",
     url: ajax_url,
     data: fd,
     contentType: false,
     processData: false,
        })
.done( function( response ) {
...
}
.fail( function( response ) {
...
}
.always( function( response ) {
...
}

Answer №1

Feel free to test out the code below. If you encounter any issues, consider the following:

var formData = new FormData( document.getElementById( 'my_form' ) );
formData.append( 'action', 'submit_data' );
$.ajax({
     type : 'POST',
     url : 'http://YOUR_SITE_URL/wp-admin/admin-ajax.php',
     dataType : 'json',
     data: formData,
     contentType: false,
     processData: false,
success : function( response ) {        
.done( function( response ) {
...
}
.fail( function( response ) {
...
}
.always( function( response ) {
...
}
} // success 
 });    // End of Ajax request

Key Points to Verify

  1. Check if the AJAX URL is correct, typically it's your_site_url/wp-admin/admin-ajax.php
  2. Verify the expected DataType is being received (e.g., 'json', 'html', or 'xml')

We hope these tips prove beneficial. Keep coding with a smile.

Answer №2

I had a situation where I needed to upload some files, but they were too large.

To resolve this issue, I went into the file /etc/php/7.0/apache2/php.ini and made the following adjustments:

upload_max_filesize = 13M
post_max_size = 27M

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to bring up the keyboard on an iPhone when focusing an HTML text field?

Currently working on developing a web app for iPhone, and looking to implement a feature where a text field is automatically focused upon page load, prompting the keyboard to appear. Despite attempting the standard Javascript method: input.focus(); I see ...

Troubleshooting Media Queries Problems in HTML and CSS

Check out the code snippet below: //Modifying text content (function() { var texts = $(".altered"); var textIndex = -1; function displayNextText() { ++textIndex; var t = texts.eq(textIndex) .fadeIn(2000) if (textIndex < te ...

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

Issue with Pure Javascript FormData upload involving files and data not successfully processing on PHP end

My file upload form follows the standard structure: <form id="attachform" enctype="multipart/form-data" action="/app/upload.php" method="POST" target="attachments"> <!-- MAX_FILE_SIZE must precede the file input field --> <i ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Regular Expression: Capturing data from a web address

Can anyone help me figure out how to extract the image ID from this URL: http://ecx.images-amazon.com/images/I/41zdz1zsG9L.SR38,50.jpg? I only need the part before the dot (41zdz1zsG9L). Any suggestions on how to achieve this using regular expressions? T ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

Using the Category ID and an optional starting number, as well as sorting the data with Mod_Rewrite - what is the best way to

I am working on converting my search page to use mod_rewrite in order to improve its functionality. The query string format I am aiming for is something like: index.php?CategoryName=Test&Start=10&Sort=1 CategoryName = TEXT [Required] - Used to l ...

Is it possible to execute MongoDB queries from an AS3 client?

Can native Javascript functions for the mongo shell be run on server side from an AS3 client AIR app? I have experience running Javascript methods embedded/loaded in HTML where SWF is also embedded, and I'm curious if it's possible to make a ser ...

JQuery failing to display image within set timeframe

In my website, I have implemented a feature that displays data from a database using auto-scrolling. As the user scrolls down the page, an AJAX function is triggered to fetch the next set of records from the database and append them to the existing content ...

The jQuery function always stops before reaching the else statement

Whenever the check_for_build button is clicked, I have been trying to verify the existence of a specific text file and then display an alert based on whether it is found or not. My approach involves checking if the file contains any text (as I intend to us ...

"Error: The function $(...).autocomplete is not recognized" in conjunction with Oracle Apex

Currently experiencing some frustration trying to solve the issue at hand. The Uncaught TypeError: $(...).autocomplete is not a function error keeps popping up and I have exhausted all resources on Stack Overflow in an attempt to fix it. This problem is oc ...

Create a navigation bar using CSS that is designed from an unordered list without any specific

Is it possible to create a multilevel menu using only CSS for the menu structure mentioned below? Websites like cssmenumaker.com showcase examples of menus with 2-3 level submenus by adding classes like has-submenu. Can we achieve this without adding any ...

refresh-free form clearing

Currently, I am working on a form that includes Recaptcha validation using jQuery. The form is functioning well as the information is sent to my email and all required fields are checked before submission. However, there is one issue that I am encounterin ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

When NuxtImg is utilized, the image will rotate 90 degrees with Nuxt3 NuxtImg

Recently, I have encountered an issue when using NuxtImg where my images appear rotated by 90°. This problem specifically arises with vertical mobile images that are read from supabase and displayed. Interestingly, the images look fine before uploading th ...

Is there a way to calculate the sum of daily values within a column using Laravel?

I need to retrieve the daily sum of the total column from an orders table that contains over 1000 records. Each day, such as Monday, Thursday, and Wednesday, has different and multiple rows in the table. How can I display the separate sum of total for each ...

Differences in React projects utilizing materialize-css compared to those using react-toolbox or material-ui

Is there a difference in technical benefits or code reliability when directly using material-css in JSX versus utilizing JSX specific libraries like material-ui or react-toolbox? Conversely, could using JSX libraries like material-ui or react-toolbox provi ...

Issue with xsl:include functionality in a Firefox extension

I've been working on a Firefox extension that utilizes XSL transformations with no issues. However, I encountered a problem when trying to perform an xsl:include from the XSL stylesheet. Upon importing the XSL stylesheet containing an xsl:include stat ...

Obtaining the XML element containing a designated attribute name

Greetings and thank you in advance, I have a question regarding the AJAX return and parsing of XML information. While I am successfully returning a request, I am fetching all the XML nodes with the tag ngPropertyName. However, I wish to retrieve only the ...