41

My ajax call output is always showing 0 as output don't know why

In functions.php I have this code

function get_data() {
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();
}

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

And my ajax call is in a javascript

$('body').on("click", ".re-reset-btn", function(e){

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

    $.ajax({
             type : "GET",
             dataType : "json",
             url : "/wp-admin/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); 

});

I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.

2
  • 1
    Check out this article, demonstrates & explains everything you need to know about implementing AJAX on both the frontend & backend: benmarshall.me/wordpress-ajax-frontend-backend Commented Jul 10, 2020 at 20:14
  • @all nice answers, but consider security also.. the nonce ..
    – bhv
    Commented Jun 19, 2021 at 9:47

9 Answers 9

44

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);
    }
});
2
  • It says my_ajax_object is not defined
    – smarttechy
    Commented Apr 22, 2017 at 10:29
  • wp_local_script please replace this as wp_localize_script now i have modified the code Commented Apr 22, 2017 at 10:35
41

Actually, WordPress comes with a handy function to access admin-ajax.

Requirements

  • In wp-admin you do not need to do anything, the js library is always loaded
  • In the front-end you need to enqueue the script wp-util, like this:

    add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
    
    function my_enqueue_function() { 
        // Option 1: Manually enqueue the wp-util library.
        wp_enqueue_script( 'wp-util' );
    
        // Option 2: Make wp-util a dependency of your script (usually better).
        wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
    }
    

The JS Library

The wp-util script contains the wp.ajax object that you can use to make ajax requests:

 wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )

Your example:

wp.ajax.post( "get_data", {} )
  .done(function(response) {
    alert("Your vote could not be added");
    alert(response);
  });

PHP code

Of course, you still need to create the wp_ajax_* hooks in your PHP script.

add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );

function my_ajax_handler() {
    wp_send_json_success( 'It works' );
}

Tip:

For Ajax responses WordPress provides two functions:

wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (i.e., they exit;)

4
  • My main question is let's say I have posted a post data like an email from jquery ajax, then is it okay to say $email = $_POST['email'] or Wordpress has some other predefined methods Commented Jun 6, 2020 at 11:16
  • Thanks god for this answer, anything above didnt work for me Commented Aug 10, 2021 at 11:56
  • wp.ajax run in localhost but not in production do you have any idea ?
    – M.Idrish
    Commented Oct 29, 2021 at 17:32
  • @prk_001 please read the "Requirements" section and make sure that your page uses wp_enqueue_script( 'wp-util' );. this is a WordPress core script and provides wp.ajax
    – Philipp
    Commented Feb 19, 2022 at 21:27
13

I had the same problem. I was new to WordPress. Therefore, I am explaining here so that every new learner can understand how ajax is calling in WordPress.

First, create a function in function.php file that resides under wp-content/theme/selected_theme folder. Here, selected_theme maybe your theme name.

In the above question, a function is created with the name get_data();

function get_data() {
    echo  "test";
    wp_die();  //die();
}

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

in the above two lines,

  1. The add_action method is used to implement the hook. Here, I am passing the two parameters, first is wp_ajax_nopriv_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.
  2. In the second add_action, I am passing the two parameters, first is wp_ajax_get_data. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.

Here, wp_ajax_nopriv call if the user is not logged in and wp_ajax called when the user is logged in.

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
    data: {
        action:'get_data', //this value is first parameter of add_action
        id: 4
    },
    success: function(msg){
        console.log(msg);
    }
});
1
  • 1
    Wow. For some reason I forgot all about the no_priv part. That solved my issue. Thanks! Commented Sep 4, 2023 at 18:47
6

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>
1
  • 4
    This code is inside a javascript file.......so its not running <?php echo admin_url('admin-ajax.php'); ?>
    – smarttechy
    Commented Apr 22, 2017 at 10:09
5
<form type="post" action="" id="newCustomerForm">

    <label for="name">Name:</label>
    <input name="name" type="text" />

    <label for="email">Email:</label>
    <input name="email" type="text" />

    <label for="phone">Phone:</label>
    <input name="phone" type="text" />

    <label for="address">Address:</label>
    <input name="address" type="text" />

    <input type="hidden" name="action" value="addCustomer"/>
    <input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>

functions.php

wp_enqueue_script('jquery');

function addCustomer() {

    global $wpdb;

    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $address = $_POST['address'];

    if ( $wpdb->insert( 'customers', array(
        'name' => $name,
        'email' => $email,
        'address' => $address,
        'phone' => $phone
    ) ) === false ) {
        echo 'Error';
    } else {
        echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
    }
    die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');

javascript

<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);

function ajaxSubmit() {
    var newCustomerForm = jQuery(this).serialize();

    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: newCustomerForm,
        success: function(data){
            jQuery("#feedback").html(data);
        }
    });

    return false;
}
</script>
1

If you are getting 0 in the response, it means your ajax call is working correctly. But, you have not defined $wpdb as a global variable in your function get_data. Check your error log, you must be seeing error there. Try:

function get_data() {
    global $wpdb;
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();
}
1

Step 1: Add ajax 'wp_enqueue_script' file in function file where you have to add other 'wp_enqueue_script' or 'wp_enqueue_style' files

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

Step 2:Now you need to create function, where you want to get response, using ajax e.g below

 add_action('wp_footer','add_ajaxex_in_footer');
   function add_ajaxex_in_footer()
    { ?>

<script type="text/javascript">
    jQuery('#sbmtbtn').click(function(){
    jQuery.ajax({
    type:"POST",
    url:my_ajax_object.ajax_url,
    data: {action:'my_special_ajax_call_enroll_cours'},
    success:function(res){
     console.log(res);
    }
   });
  });</script><?php 
 }

Step 3: Now you have to create function where you have to write query,

add_action('wp_ajax_my_special_ajax_call_enroll_cours', 'enroll_cours');
add_action('wp_ajax_nopriv_my_special_ajax_call_enroll_cours', 'enroll_cours');

 function enroll_cours()
 { 
     echo "Here you van write Query or anything"; 
     exit;
 }

=> If you want to fire ajax request after onClick button, just pass the button ID

<input type="button" id="sbmtbtn" name="Save">
0

Here how to make in plain vanilla js the AJAX call in WordPress.

var urlToajax=jsajaxe_S.ajaxurl;


function P_lifg(){ 

 var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
  document.getElementById("demo").innerHTML = this.responseText;
  document.getElementById("demo2").innerHTML = urlToajax+ "?action=testfirst";
  }
};


  xmlhttp.open("GET", urlToajax+ "?action=testfirst", true);    
  xmlhttp.send(0);

}

See on this blog, what to add functions.php and template html to get this work, also reasonings why there is no data in vanilja js unlike jQuery, but just action

Here add_actions in functions.php:

add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );       
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');

Add this function over that, here now this function:

 function FunctionTF(){

 exit( "Hola hola" );
    
} 

See explanation why? code in "exit" in my blog

Here add this html on some wp-template

 <div id="demo"></div>
 <div id="demo2"></div>
 <button id="spesial_button" onclick="P_lifg()">I am spesial</button>

See rest in: https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html

0
add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {
   wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/my_plugin/my_voter_script.js', array('jquery') );
   wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'my_voter_script' );

}
2
  • Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Yunnosch
    Commented Apr 18, 2023 at 7:36
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Apr 20, 2023 at 10:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.