0

I am trying to get a response from ajax request in wordpress. But every time I am trying to do the request it gets 0 as the response. Below is my code in java script

$("#submit").click(function(e) {
 e.preventDefault();
var ajaxurl = '/WordPress/wp-admin/admin-ajax.php';
  alert(dataString);

$.post( ajaxurl, 
    {
        'action': 'my_action',
        'data':   'name'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
);

});

in the function.php

add_action('wp_ajax_my_action','data_insert');
add_action('wp_ajax_nopriv_my_action','data_insert');

function data_insert()
{

    echo "hello";

    die;

}
Waters Sharma
  • 68
  • 1
  • 2
  • 11

2 Answers2

1

Here you go:

JavaScript:

$(document).ready(function() {
    $("#submit").click(function(e) {
        var demo = 'demo';
        var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
        data = { action: "data_insert", demo: demo};     
        $.ajax({
            url: ajaxurl,
            data: data,
            dataType: 'json',
            type: 'post',
            success: function(response) {
              console.log(response);  
            }
        });
    });    
});

PHP:

add_action('wp_ajax_data_insert', 'data_insert');
add_action('wp_ajax_nopriv_data_insert', 'data_insert');
function data_insert() {
    $data = $_POST['demo'];
    echo json_encode($data);
    die();
}
Noman
  • 1,459
  • 2
  • 18
  • 38
0

You have to localize your script file if you are using an external js file in order to call the AJAX in WordPress.

Suppose your js file is custom.js

$("#submit").click(function(e) {
 e.preventDefault();
$.post( front_ajax.ajaxurl, 
    {
        'action': 'my_action',
        'data':   'name'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
);

});

Functions.php File

function my_enqueing_function() {
    wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() .'your_path_here/custom.js', array('jquery'), time(), true );
    //Localizing our custom-js script to be called using front_ajax
    wp_localize_script( 'custom-js', 'front_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) );
}

add_action('wp_ajax_my_action','data_insert');
add_action('wp_ajax_nopriv_my_action','data_insert');
function data_insert()
{
    echo "hello";
    wp_die;
}

Try the above. Should work.

DpEN
  • 4,216
  • 3
  • 17
  • 26