36

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.

Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
smarttechy
  • 852
  • 1
  • 9
  • 23
  • 1
    Check out this article, demonstrates & explains everything you need to know about implementing AJAX on both the frontend & backend: https://benmarshall.me/wordpress-ajax-frontend-backend/ – Ben Marshall Jul 10 '20 at 20:14
  • @all nice answers, but consider security also.. the nonce .. – bhv Jun 19 '21 at 09:47

9 Answers9

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);
    }
});
Vigneshwaran J
  • 548
  • 4
  • 13
36

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

Philipp
  • 10,240
  • 8
  • 59
  • 71
  • 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 – Karue Benson Karue Jun 06 '20 at 11:16
  • Thanks god for this answer, anything above didnt work for me – Jason Derrick Aug 10 '21 at 11:56
  • wp.ajax run in localhost but not in production do you have any idea ? – M.Idrish Oct 29 '21 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 Feb 19 '22 at 21:27
9

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);
    }
});
moghwan
  • 1,829
  • 2
  • 17
  • 29
Sumit Kumar Gupta
  • 2,132
  • 1
  • 22
  • 21
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>
Talk Nerdy To Me
  • 626
  • 5
  • 21
Shital Marakana
  • 2,817
  • 1
  • 9
  • 12
4
<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>
Talk Nerdy To Me
  • 626
  • 5
  • 21
iamasp
  • 87
  • 5
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();
}
Talk Nerdy To Me
  • 626
  • 5
  • 21
Awais Umar
  • 2,027
  • 3
  • 27
  • 46
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">
Jiří
  • 415
  • 6
  • 16
Aslam Khan
  • 382
  • 2
  • 2
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

Narutofan
  • 9
  • 6
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' );

}

  • Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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 Apr 18 '23 at 07: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](/help/how-to-answer). – Community Apr 20 '23 at 10:09