In spite of many similar posts, all the proposed solutions didn’t work for me, so here we are.

I have the following script :

jQuery('#term').keyup(ajaxChange);

        function ajaxChange(){
            var newFormChange = jQuery("#term").val();
            alert (newFormChange);
            jQuery.ajax({
                type:"POST",
                action: "my_test_action",
                url: "/wp-admin/admin-ajax.php",
                data: newFormChange,
                success:function(data){
                    console.log(data);
                }
            });

        return false;
        }

And the PHP looks like this :

function my_test_action() {

    $var = "this is a test";
    wp_send_json($var);

    die();
}

add_action( 'wp_ajax_my_test_action', 'my_test_action' );
add_action( 'wp_ajax_nopriv_my_test_action', 'my_test_action' );

I’ve also tried : echo json_encode($var) or echo $var, instead of wp_send_json() but the function always returns 0 in the browser console !

My other AJAX calls work, for instance I have another one that calls a PHP script which calls a WP Query and displays some posts, it works fine.

EDIT : Here is how my script is included :

 function add_js() {

         if (is_page_template()) {
            wp_enqueue_script( 'mycustomscript', get_stylesheet_directory_uri().'/js/mycustomscript.js', array('jquery'), '1.0', true );

            wp_localize_script('mycustomscript', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
        }
    }
    add_action('wp_enqueue_scripts', 'add_js');

I think the problem comes from the newFormChange variable, because jQuery(this).serialize(); didn’t work in the first place, because the form is not submitted but only one of its fields changes. So I replaced it by var newFormChange = jQuery("#term").val(); but then maybe there is a problem with url: "/wp-admin/admin-ajax.php"

Where am I mistaken ? Thanks

3 Answers
3

Note that the action should be inside the data key. In your post request there is no key named as action therefore, the callback function is never being called.

Consider this example:-

jQuery.ajax({
    type:"POST",
    url: "/wp-admin/admin-ajax.php",
    data: { 
        action: "my_test_action",
        form_data : newFormChange
    },
    success: function (data) {
        console.log(data);
    }
});

Also Note: Never use relative Ajax URL like /wp-admin/admin-ajax.php. You can use wp_localize_script(). See these examples

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *