Ajax is a key technology for creating responsive and dynamic interactive features. In WordPress, utilizing Ajax helps to improve website functionality and enhance user experience. However, at times, errors may occur when handling Ajax calls. In this article, we will explore how to use Ajax in WordPress and address common errors such as 404 and 400 (Bad Request).
How to use Ajax in WordPress and fix 404, 400 (Bad Request) errors
Step 1: Register File and declare Ajax values
Registering the file and declaring Ajax values means that we will include the file custom-ajax.js
to run in the browser and define the required values for the functionality that needs to be processed. In this tutorial, ItsmeIT will demonstrate how to code and use Ajax in WordPress plugin.
function enqueue_custom_ajax_script(){ wp_enqueue_script('handle-ajax-name', plugin_dir_url(__FILE__) . 'js/custom-ajax.js', array('jquery'), $this->version, false); wp_localize_script('handle-ajax-name', 'custom_ajax_vars', array( 'custom_ajax_url' => admin_url('admin-ajax.php') )); } add_action( 'wp_enqueue_scripts', 'enqueue_custom_ajax_script' );
In there:
wp_enqueue_script
: This function is used to register the JavaScript file to be used in WordPress. If you have placed the file in the plugin’s JavaScript folder, you can useplugin_dir_url(__FILE__)
. Alternatively, if you are working infunctions.php
, you can utilizeget_template_directory_uri() . '/path/to/custom-ajax.js'
.wp_localize_script
: This function is used to declare values within the JavaScript file. In this example, ItsmeIT will declare a variable calledcustom_ajax_url
to store the URL for the Ajax actions. This ensures successful usage of Ajax in WordPress.
Note: If you want to put add_action
in construct() then you need to add $this.Example: add_action( ‘wp_enqueue_scripts’, array($this, ‘enqueue_custom_ajax_script’));
Step 2: Create JavaScript File to write Ajax handling code
Next, after registering the custom-ajax.js
JavaScript file as mentioned earlier, let’s proceed to create this file. In this file, we will write the code to send the Ajax request and handle the response.
(function ($) { $(function () { $('#my-button').click(function () { $.ajax({ url: custom_ajax_vars.custom_ajax_url, type: 'POST', data: { action: 'custom_ajax_callback', param: 'value', // Tham số tùy chọn }, success: function (response) { // Xử lý kết quả thành công console.log(response); }, error: function (xhr, status, error) { // Xử lý lỗi console.log(xhr.responseText); } }); }); }); })(jQuery);
In there:
url: custom_ajax_vars.custom_ajax_url
refers to the URL we declared in step 1, so we can use it in the JavaScript file. If you want to add other values, you just need to declare them in a similar manner.action: 'custom_ajax_callback'
represents the action that will trigger the hook declared usingwp_ajax
. ItsmeIT will demonstrate this in the next step.
Step 3: Register and process Ajax send request
Next, we need to register and process the Ajax request in WordPress.
// Register Ajax request add_action('wp_ajax_custom_ajax_callback', 'custom_ajax_handler'); add_action('wp_ajax_nopriv_custom_ajax_callback', 'custom_ajax_handler');
Explanation:
wp_ajax
: This is the event declaration for when a user is logged in.
wp_ajax_nopriv
: This declares the event for when a user is not logged in.
custom_ajax_callback
: Give it a suitable name and ensure that in the JavaScript file you have called the action using this name.
custom_ajax_handler
: This will invoke the PHP function. If you have declared add_action()
within the __construct()
function, then you need to include $this
as ItsmeIT mentioned in step 1.
To make an Ajax call to a WordPress function, PHP code is essential. Now, let’s proceed to write the custom_ajax_handler()
function to handle the Ajax request.
// Handle Ajax request function custom_ajax_handler() { $response = [ 'success' => 'errors', 'message' => 'message for errors' ]; // Xử lý yêu cầu Ajax ở đây if (isset($_POST['param']) && $_POST['param']) { // todo $response = [ 'success' => 'true', 'message' => 'message for success' ]; } else { // todo $response = [ 'success' => 'false', 'message' => 'message for false' ]; } // Kết thúc quá trình xử lý Ajax và trả về response wp_send_json_success($response); wp_die(); }
How to fix 404 and 400 (Bad Request) errors in Wordpress
When using Ajax in WordPress, a 404 or 400 (Bad Request) error may occur. Here are some solutions to fix these errors:
- Error 404: This error usually occurs when the URL of the Ajax request is either not defined correctly or cannot be found. Ensure that the
url
in the Ajax request points to the correct address of the Ajax handler file. Let’s review how ItsmeIT declared the “wp_localize_script” and “ajax URL” in step 1 and step 2. - Error 400 (Bad Request): This error occurs when the data sent in the Ajax request is invalid or does not properly respond to the request. Make sure that the data sent in the Ajax request is properly formatted and matches the processing of the Ajax request. You can refer back to step 3 where we declared “wp_ajax” and “wp_ajax_nopriv”.
In addition, there can be other causes of this error, for example an error in the processing of the Ajax request or a conflict with other plugins. Check the error log or message to see the details of the specific error and find the right solution.
Using Ajax in WordPress helps to create responsive and interactive website functionality quickly. By creating a JavaScript file and registering an Ajax request handler, we can leverage the power of this technology.
– Advertising –