Support » Developing with WordPress » jQuery and Ajax callback

  • Resolved Marco

    (@jrmarco)


    Hi everyone,
    I’m starting to work with jQuery and Ajax inside a wordpress plugin for the first time and I’m having lots of issue. I’ve read the guide but something is missing anyway. I’m doing a simplce script that read text from a textfield and print it inside some element. I have 3 file :

    – page.php : the page with jquery e ajax call
    – pluginpage.php : the main plugin page
    – action.php : the php file that elaborate the ajax call

    Page.php :

        jQuery("#button").click(function() { 
            var text_capture = jQuery("#text").val();
            jQuery.post(my_ajax_obj.ajax_url, {
               _ajax_nonce: my_ajax_obj.nonce,
                action: "text_writer",
                text: text_capture
            }, function(result) {
                jQuery("#parag").append(result);
            });
        });
    
    HERE ALL THE HTML ELEMENT WITH TEXTFIELD etc. etc.
    

    Pluginpage.php :

    require_once(PATH_PLUGIN_ETC....'action.php');
    add_action( 'wp_ajax_text_writer', 'text_writer' );

    Action.php :

    function text_writer() {
    return $_POST['text'];
    }

    Unfortunately this doesn’t append the text inside the textfield. Where am i doing wrong?

Viewing 8 replies - 1 through 8 (of 8 total)
  • what type response for your output ? html. Use echo and close with die, if json I would like to use wp_send_json_success.

    Thread Starter Marco

    (@jrmarco)

    The return it’s mixed. In this example I’m only trying to return the text value read, but it can be an integer, a string, a JSON or whatever. I only need to understand where the function stops. Let me rewrite the code and see if I got where is the issue

    • This reply was modified 6 years, 3 months ago by Marco.
    Moderator bcworkz

    (@bcworkz)

    Because your jQuery is on a PHP page, I’m guessing that either the correct jQuery library is not loaded or that my_ajax_obj.ajax_url is not properly defined. When following tutorials, it’s best to not deviate from how things are done, at least until you fully understand what’s going on so you can make proper deviations.

    There are reasons the jQuery in the tutorial is on it’s own .js file and it is enqueued through a hook to ‘wp_enqueue_scripts’. One of them being that wp_localize_script() can be called to establish the value of my_ajax_obj.ajax_url

    Thread Starter Marco

    (@jrmarco)

    I wrote another code because the example doesn’t work for me. I totally rewrote my example code with the right rules now, but it won’t reply anyway :/ So the new code is set up like this :

    Plugin page :

    wp_enqueue_script("jquery");
    add_action( 'wp_enqueue_scripts', 'ajax_writecode' );	
    function ajax_writecode() {
    	wp_enqueue_script( 'doSome', plugins_url( 'js/script.js', __FILE__ ) );
    	wp_localize_script( 'doSome', 'doSomeCallback', array(
    		'ajax_url' => admin_url( 'admin-ajax.php' )
    	));	
    }		
    		
    add_action('wp_ajax_manipulate','manipulate');
    function manipulate() {
    	echo $_REQUEST['text'].' Catch by manipulate() ';
    	die();
    }

    The HTML page with the form :

    <form method="post">
    	<textarea id="result"></textarea>
    	<input id="btn" type="button" value="Write" />
    	<input id="text" type="text">
    </form>

    The script.js :

    jQuery("#btn").on( 'click', function() {
    	var text = jQuery("#text").val();
    	jQuery.ajax({
    		url : doSomeCallback.ajax_url,
    		type : 'post',
    		data : {
    			action : 'manipulate',
    			text : text
    		},
    		success : function( response ) {
    			jQuery('#result').append( response );
    		}
    	});
    
    	return false;
    })

    Still nothing comes :\

    Moderator bcworkz

    (@bcworkz)

    Any call to wp_enqueue_script() must occur within a callback to one of a few limited hooks, ‘wp_enqueue_scripts’ for front end scripts. Admin and login scripts have different hooks. Specify your own script is dependent on array(‘jquery’) in the wp_enqueue_script() call for your own script as a third argument.

    Check you page’s HTML source in your browser to ensure the related external references in the head section has the correct paths. It’s surprisingly easy to get these wrong. Also verify dependencies are loaded before the scripts that are dependent on them.

    Be sure you are logged in when you test your AJAX call.

    Thread Starter Marco

    (@jrmarco)

    I found the error. I didn’t see that i was declaring the wp_enqueue_script() and wp_localize_script() inside the function that define a submenu. I moved them outside in the main definition and works like a charm. But I have another question now : Is it possible to define wp_enqueue_script() and wp_localize_script() inside a submenu definition or they must reside in the main only?

    For ex. I have :

    add_menu_page( 'SomePlugin', 'SomeP', 'manage_options', 'somep', 'init_func' );
    add_submenu_page( 'somep', 'SomeSub - Page', 'Subpage','manage_options', 'somep_page' ,'sub_func');

    Inside the init_funct() i define wp_enqueue_script() and wp_localize_script() and works perfectly. If I put them in sub_func() when the subpage is called they won’t produce output. I already checked that with the subpage everything is included ( jquery, script.js, etc. )

    EDIT :
    I tried to include everything inside another function and the result is the same, seems like isn’t called from the page. Let me add. In the main plugin I have :

    function utility($hook) {
    	require_once(PATH.'utility.php');
    }
    add_action( 'admin_enqueue_scripts', 'utility' );
    

    The utility contains the following :

    
    function doSome() {
    	wp_enqueue_script( 'doSome', plugins_url( 'js/script.js', __FILE__ ),array('jquery'), '1.0', true );
    	wp_localize_script( 'doSome', 'doSomeCallback', array(
    		'ajax_url' => admin_url( 'admin-ajax.php' )
    	));
    }	
    			
    function manipulate() {
    	echo $_POST['text'];
    	die();
    }
    	
    add_action( 'admin_enqueue_scripts', 'doSome' );
    add_action('wp_ajax_manipulate','manipulate');
    • This reply was modified 6 years, 3 months ago by Marco.
    • This reply was modified 6 years, 3 months ago by Geoffrey Shilling.
    Moderator bcworkz

    (@bcworkz)

    It depends on when and where you attempt to add your callback. The various enqueue scripts actions fire fairly late, so it should be OK in most scenarios. However, in your particular example it’s too late by a hair.

    ‘admin_enqueue_scripts’ only fires once per request. So requiring utility.php works fine. But since ‘admin_enqueue_scripts’ already fired to add utility.php, attempting to add another callback to ‘admin_enqueue_scripts’ from within that file is fruitless because ‘admin_enqueue_scripts’ had already fired.

    The thing to do would be to enqueue directly from within utility() or to enqueue in utility.php without adding an action callback. Just call wp_enqueue_script() directly.

    Thread Starter Marco

    (@jrmarco)

    Perfect. Now I got it. Thanks @bcworkz
    Have a nice day!

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘jQuery and Ajax callback’ is closed to new replies.