Why is my WordPress AJAX call returning 0?

Barbara Streisand
Release: 2024-11-01 14:05:02
Original
396 people have browsed it

Why is my WordPress AJAX call returning 0?

Ajax Calls in WordPress: Troubleshooting Output Issues

Your ajax call is always returning 0 as output, leaving you perplexed about the cause. To rectify this issue, consider the following:

Global ajaxurl Variable in WordPress:

WordPress defines the global ajaxurl variable in the backend, which facilitates AJAX calls. However, this variable is not available in the frontend.

Define ajaxurl in Frontend:

To utilize AJAX calls in the frontend, you need to manually define the ajaxurl variable. One effective method is through wp_localize_script.

Using wp_localize_script:

Assuming your AJAX calls reside in my-ajax-script.js, use wp_localize_script as follows:

function my_enqueue() {
    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
    wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
Copy after login

This creates a my_ajax_object object in your JS file, which contains the ajax_url.

Utilize my_ajax_object in Javascript:

After localizing your script, utilize the my_ajax_object object in your JS file:

<code class="js">jQuery.ajax({
    type: "post",
    dataType: "json",
    url: my_ajax_object.ajax_url,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});</code>
Copy after login

The above is the detailed content of Why is my WordPress AJAX call returning 0?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!