Support » Developing with WordPress » AJAX request not working

  • I’m developing a “hangman” plugin, and when someone types [hangman] on page, it would be possible to play the hangman. Everything seems to be working fine, but the ajax request is not working. It gives a “Fatal error: Call to undefined function is_admin() in /var/www/html/wptest/wp-content/plugins/hangman/hangman.php”.

    “hangman.php” (I removed some of the code for better understanding)
    =============

    
    !is_admin() && add_shortcode('hangman', 'hangman_creation');
    
    function hangman_creation(){
    	if(isset($_GET['action']))
    	$action = $_GET['action'];
    	elseif(isset($_POST['action']))
    	$action = $_POST['action'];
    	else
    	$action = 0;
    
    	switch($action)
    	{
    		case 0: // Title
    						
    			require 'title.php';
    				
    			break;
    			
    		case 1: // Start
    			require 'start.php';
    			
    			break;  
    	}
    
    }
    
    !is_admin() && add_action('wp_ajax_hangman_ajax', 'hangman_ajax');
    !is_admin() && add_action('wp_ajax_nopriv_hangman_ajax', 'hangman_ajax');
    
    // AJAX CALL.
    function hangman_ajax()
    {	
    	$response = array();
    	
            // More code
    
    	echo json_encode($response);	
    }
    
    !is_admin() && add_action('init', 'register_scripts');
    
    function register_scripts()
    {
        wp_enqueue_script('hangman_script', plugins_url('/js/script.js', __FILE__), array('jquery' ));
        wp_enqueue_style('hangman_style', plugins_url('/css/style.css', __FILE__));
    }

    “script.js”
    ==============

    jQuery(document).ready(function($){
    	jQuery(".letter").click(function(){		
    		$.ajax({
    			data: {letter: $(this).text(), action: 2},
    			type: "POST",
    			dataType: "json",
    			url: "http://localhost/wptest/wp-content/plugins/hangman/hangman.php?action=hangman_ajax",
    			context: this,
    			success: function(data)
    			{
    	// This is never executed
    			},
    			error: function (jqXHR, textStatus, errorThrown)
    			{
                                  alert(errorThrown); // RETURNS "PARSERERROR"
    			}
    		});
    	});
    });
    • This topic was modified 4 months, 2 weeks ago by  oligalma.
    • This topic was modified 4 months, 2 weeks ago by  oligalma.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Based on your code, the URL for your AJAX request should point to wp-admin/admin-ajax.php. However, please be aware that wp-admin-ajax.php loads all of WordPress (including plugins and theme), which means your game will probably cause server issues.

    You would be much better off splitting your code in two. The first part would include all but the hangman_ajax() function and the two lines with the wp-ajax_* action hooks (they aren’t needed), and the second would only include the contents of the hangman_ajax() function. You could then use the URL to the second part in your AJAX request.

    Thanks @diondesigns. I splitted the code in two, as you said, and now it’s working. However I also had to add some sessions code, as it is said in this page: https://silvermapleweb.com/using-the-php-session-in-wordpress/

    Now I have another problem. In the ajax.php I can’t use WordPress functions (they don’t work). What should I do? For exemple, I get this error: “Call to undefined function plugins_url()”

    • This reply was modified 4 months, 2 weeks ago by  oligalma.
    • This reply was modified 4 months, 2 weeks ago by  oligalma.

    There are a couple ways to deal with your issue, both of which involve passing another value in the POST data. One is to pass the value of plugins_url(). This is the simplest option, but it would only be effective if that is only data you require from WordPress.

    Another is to pass the portion of __DIR__ that is not in ABSPATH, use that data in your AJAX handler to locate wp-load.php, and then load a partial version of WordPress. That would give you access to the get_option() function, which would let you construct the base URL to your plugin directory. It is also possible to load WordPress without the theme and plugins, but loading WP_CRON and the REST API in an AJAX hander is not a good idea, so it would be a “last resort” option.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.