• Resolved danieltj

    (@danieltj)


    I’m trying to get my AJAX request working and regardless of what I try, it always returns 0 and I’ve looked everywhere to find a solution and nothing works at all. This is the code I have right now.

    JavaScript:

    jQuery(document).ready(function($) {
    
    	$('.button').on('click', function(e) {
    	
    		e.preventDefault();
    	
    		$.ajax({
    
    			data: {
    				action: 'my_action',
    				data: 'test'
    			},
    			type: 'post',
    			url: PLUGIN.ajax_url,
    			success: function(response) {
    
    				console.log(response);
    			
    			}
    		
    		});
    	
    	});
    
    });

    PHP:

    function ajax_callback() {
    
    	echo "test";
    	exit();
    
    }
    add_action('wp_ajax_noprov_my_action', 'ajax_callback');
    add_action('wp_ajax_my_action', 'ajax_callback');

    What am I doing wrong here? The script is included properly and is clearly running. I’m expecting to just print “test” into the console just to know it works but it’s not even doing that.

    Any ideas?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator t-p

    (@t-p)

    wordpress.stackexchange.com has a few threads that might worth reviewing:

    https://wordpress.stackexchange.com/search?q=AJAX+request+returns+0

    Moderator bcworkz

    (@bcworkz)

    If this happens only when not logged in, it’s because you’ve hooked the wrong action. Well, right action with a typo actually:
    wp_ajax_noprov_my_action should be wp_ajax_nopriv_my_action

    Thread Starter danieltj

    (@danieltj)

    That was just a minor typo, I wasn’t relying on the nopriv action anyway because what I’m trying to achieve requires an admin with the wp-admin area. No matter what I do I can only get it to return 0. I know it’ll be super obvious but nothing is working regardless of how many articles I read.

    Moderator bcworkz

    (@bcworkz)

    I had no doubt it was a typo. Code is not tolerant of typos, minor or otherwise, speaking from a great depth of experience with typos ?? If the user is must be logged in, there is no point in hooking nopriv. Just sayin’. It doesn’t matter much if you do as long as capability checks are done. Then it would not be the cause of the 0s anyway.

    Something server side is not executing (I think). Where did you place your PHP code? How is your jQuery script and jQuery loaded? How is PLUGIN.ajax_url defined, what is its value? Better yet, post the remainder of any relevant code.

    Thread Starter danieltj

    (@danieltj)

    I managed to fix this just by chance. For some reason WordPress didn’t like the fact that I had my action hook was included within a file that was included within another file. I moved the hook up a file and it seems to work. Very weird.

    I think it might have been out of scope somehow.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘AJAX request returns 0’ is closed to new replies.