close

How to call ajax in WordPress

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to call ajax in WordPress in php. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How to call ajax in WordPress Error Occurs?

Today I get the following error How to call ajax in WordPress in php.

How To Solve call ajax in WordPress Error ?

  1. How To Solve call ajax in WordPress Error ?

    To Solve call ajax in WordPress Error This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

  2. How to call ajax in WordPress

    To Solve call ajax in WordPress Error This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

Solution 1

In backend there is global ajaxurl variable defined by WordPress itself.

This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

Good way to do this is to use wp_localize_script.

Let’s assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:

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' );

After localizing your JS file, you can use my_ajax_object object in your JS file:

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: my_ajax_object.ajax_url,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});

Solution 2

Add admin-ajax.php by using admin_url('admin-ajax.php');

<script type="text/javascript">
    $('body').on("click", ".re-reset-btn", function(e){

        var panel = $('#re-compare-bar');

        $.ajax({
            type : "POST",
            dataType : "json",
            url : "<?php echo admin_url('admin-ajax.php'); ?>",
            data : {action: "get_data"},
            success: function(response) {
                alert("Your vote could not be added");
                alert(response);
            }
        });

        $("#re-compare-bar-tabs div").remove();
        $('.re-compare-icon-toggle .re-compare-notice').text(0);

    });
</script>

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment