• Resolved Timjwp

    (@timjwp)


    I have created a plugin and am submitting ajax requests from the front end.

    The problem is my ajax hook does not appear to be registered when the request reaches admin-ajax.php

    I can implement a core hack adding my action hook and callback function inside admin-ajax.php and everything seems to work. It’s interesting to note that I must add the callback function to admin-ajax.php or it does not see the function inside my plugin functions.php file and won’t work.

    Am I correct in thinking my plugin is registered incorrectly?

    Any ideas out there?

    TIA

Viewing 9 replies - 1 through 9 (of 9 total)
  • Can you show me your hook? Please note there are 2 types of ajax hooks:

    Admin only:
    add_action( 'wp_ajax_{your_action}', 'your_public_function' );

    Public:
    add_action( 'wp_ajax_nopriv_{your_action}', 'your_public_function' );

    These functions set up the AJAX call – your_action is the action defined in your AJAX request.

    You also need to localize the ajax script itself.

    Admin (dashboard only):
    add_action( 'admin_print_scripts-index.php', 'enqueue_scripts' );

    Admin (all pages):
    add_action( 'admin_print_scripts', 'enqueue_scripts' );

    Frotn End:
    add_action( 'wp_print_scripts', 'enqueue_scripts') );

    Here, the ‘enqueue_scrupts’ is the function that will enqueue the scrip with your AJAX call in it, and localize the AJAX link:

    function enqueue_scripts() {
        // Your actual AJAX script
        wp_enqueue_script( 'my-script', '/js/script.js', array( 'jquery' ) );
        // This will localize the link for the ajax url to your 'my-script' js file (above). You can retreive it in 'script.js' with 'myAjax.ajaxurl'
        wp_localize_script( 'my-script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    Thread Starter Timjwp

    (@timjwp)

    Thanks for the quick response.

    For testing I use both hooks but when live users will need to be logged in.

    I am also localizing scripts though the hook I am using is add_action(‘wp_enqueue_scripts’, ‘my_enqueue_function’). I’m fairly certain none of this is the problem.

    Not sure if I was clear enough. I’m sure the ajax request is sent so that isn’t the problem. The problem is when the request reaches admin-ajax.php the hook does not seem to be registered any longer. I have tested this using has_action() in admin-ajax.php

    By adding the hook and call back function just before do_action() in admin-ajax.php I can determine that everything is processed without any errors so something must be removing my hook.

    Let me know what info I can provide to help identify the problem.

    Thanks again

    Okay, for starters don’t put anything in any core files (admin-ajax.php). You can do everything from the THEME level, that way when you update WordPress you won’t lose your alterations (and on that note, use a child theme, or else you will lose changes when you update the theme).

    Back to it:

    I am assuming the following:
    – you are localizing your ajax link onto your own js file which contains a ajax call to “your_action”.
    – you have add_action( ‘wp_ajax_nopriv_your_action’, ‘your_function’ );
    – you have defined ‘your_function’ and are returning a JSON encoded value.

    Could you give me an example of your JS code that you are using? After I see that it’s all in order, my only solution for you would be for me to make you a quick example of a working ajax call.

    Thread Starter Timjwp

    (@timjwp)

    Thanks for the advice.

    I do know and implement WordPress development best practices. I am only editing core files on a dev setup for testing purposes to determine where the ajax is failing.

    I’m using a child theme but the ajax posting from front end is being developed as a plugin not in the theme files (other than the form).

    All your assumptions are correct.

    Please keep in mind that the whole process works when I add the action hook and callback function inside admin-ajax.php. This means that the code I am using is working. I have tested if the hook exists before adding it in admin-ajax.php and it doesn’t. So my hook is either not being registered for some reason or it’s being removed before the ajax request is sent.

    Here is the code in my js file.

    // JavaScript Document
    function ajaxSubmit(){
    
    	var formdata = jQuery(this).serialize();
    	formdata = formdata.replace(/%5B/g,'-').replace(/%5D/g,'');
    	formdata = 'action=edit_jobpost&'+ formdata + '&wpcf_action=cd_verify&security='+editpostnonce+'&_wpnonce='+wpnonce;
    	var update = jQuery(this).find('.wpcf-repetitive-response');
    
    	jQuery.ajax({
    		url: ajaxurl,
    		type: 'post',
    		dataType: 'json',
    		data: formdata,
    		beforeSend: function() {
    				jQuery('#wpcf-fields-under-title').hide();
                    jQuery('#wpcf-ajax-response').addClass('wpcf-ajax-loading');
                },
    		success: function(data, textStatus, XMLHttpRequest) {
                var id = '#feedback';
                jQuery(id).html('');
                jQuery(id).append('Your job post update was successful');
            },
     	});
    	return false;
    }

    Hm.. Not sure then man.

    Your jQuery script looks clean (obviously) and it removes any doubts I had previously regarding your enqueueing..

    One thing I realized during my last AJAX encounter was I forgot to return a JSON encoded value.

    Perhaps a good idea would be to make an extremely simple version of your ajax call, to isolate whether the problem definitely is the php callback for your action, or whether it has to do with the call itself from jQuery.

    something as simple as:

    jQuery.ajax({
    		url: ajaxurl,
    		type: 'post',
    		dataType: 'json',
    		data: array(action: 'test_action'),
    		success: function(data, textStatus, XMLHttpRequest) {
                alert(data.value);
            },
     	});

    php:

    add_action( 'wp_ajax_nopriv_test_action', 'your_public_function' );
    
    function your_public_function($args) {
        $data = array( 'test' => 'test' );
        return json_encode( $data );
        exit;
    }

    Thread Starter Timjwp

    (@timjwp)

    Something new to note.

    I tried to use my plugin directory path ‘SWFEPATH’ defined in my plugin in admin-ajax.php defined as such;

    define('SWFEPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );
    
    This returned an error.
    
    So I determined that the path definition (and subsequently the action hook) did not exist because my plugin had been deactivated at some point when it generated an error.
    
    So now the hook does exist and fires at the ajax request but the new problem is it doesn't see my callback function... ?
    
    My code in functions.php looks like this;

    function edit_post(){

    // generate the response

    $my_post = array();
    $my_post[‘ID’] = $_POST[‘post_ID’];
    $my_post[‘post_status’] = ‘publish’;
    $my_post[‘post_content’] = ‘This is the updated content.’;

    // Update the post into the database
    wp_update_post( $my_post );

    $response = json_encode( array( ‘success’ => true, ‘data’ => ‘Your job post update was successful’ ) );

    // response output
    header( “Content-Type: application/json” );
    echo $response;
    die();
    }

    add_action(‘wp_ajax_edit_post’, ‘edit_post’);`

    and the error is;

    <br />
    <b>Warning</b>:  call_user_func_array() expects parameter 1 to be a valid callback, function 'edit_post' not found or invalid function name in <b>C:\xampp\htdocs\devsetup\wp-includes\plugin.php</b> on line <b>403</b><br />
    0

    So it does not see my function.

    Any thoughts on why that could be?

    Is your plugin inside a class? If not, I would STRONGLY suggest changing your function name. edit_post is an already defined WordPress function in the core.

    Preferable something as simple as “sfze_edit_post” – something that will never be replicated.

    Thread Starter Timjwp

    (@timjwp)

    My function name was more specific I just used that here.

    I have got it all working so and I really appreciate you hashing this out with me cause I’ve been working this out for a while now.

    The problem was I had required my function.php when loading the form so all my functions were visible from there but I didn’t require it in my main plugin file so it wasn’t defined from within admin-ajax.php.

    That coupled with the fact that my original ajax request (days ago) was incorrect and not thinking about the fact that the plugin might not be active because of errors just had me going down the wrong road.

    Thanks again I do appreciate it!

    No problem. Glad you got it working 🙂

Viewing 9 replies - 1 through 9 (of 9 total)
  • The topic ‘admin-ajax from front end – hook not registered’ is closed to new replies.