Home > Article > Backend Development > 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' );
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>
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!