Home  >  Article  >  Backend Development  >  How to Make Ajax Calls in WordPress Without Plugins?

How to Make Ajax Calls in WordPress Without Plugins?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 06:06:02966browse

How to Make Ajax Calls in WordPress Without Plugins?

Calling Ajax in Wordpress Without Plugins: A Comprehensive Guide

As mentioned in the original issue, making Ajax calls in Wordpress without utilizing plugins can sometimes result in unexpected outcomes, such as always displaying "0" as the output. This is due to the absence of a global variable called ajaxurl in the frontend. Wordpress creates this variable during runtime but only makes it available on the backend.

To resolve this issue, it is necessary to create your own ajaxurl variable in the frontend using the wp_localize_script function. Here's an example of how to do this:

<code class="php">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' );</code>

This code will create a global my_ajax_object object in the frontend, which contains the ajax_url property. You can then use this object in your Javascript code to make Ajax requests, like so:

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

By utilizing this approach, you can successfully make Ajax calls in Wordpress without relying on plugins. Remember to modify the ajax-script filename and CDN links to match your project's setup.

The above is the detailed content of How to Make Ajax Calls in WordPress Without Plugins?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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