PHP code example of oberonlai / wp-ajax

1. Go to this page and download the library: Download oberonlai/wp-ajax library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

oberonlai / wp-ajax example snippets




use ODS\Ajax;

class MyAjax extends Ajax { ... }




use ODS\Ajax;

Class ExampleAction extends WP_AJAX{

    protected $action = 'example-action';

    protected function run(){

    	// Your Code Here!
    	
    	update_option('name', $this->get('name'));

    }
}
ExampleAction::listen(); // Don't forget this line.

ExampleAction::url() // http://example.com/wp-admin/admin-ajax.php?action=example-action
ExampleAction::url(['name' => 'Anthony Budd']) // http://example.com/wp-admin/admin-ajax.php?action=example-action&name=Anthony%20Budd

Example::url() // Returns the url of the ajax endpoint. Example http://ajax.local/wp/wp-admin/admin-ajax.php?action=example

$this->isLoggedIn(); // Returns TRUE or FALSE if the current visitor is a logged in user.

$this->has($key); // has() will return TRUE or FALSE if an element exists in the $_REQUEST array with a key of $key

$this->get($key, [ $default = NULL ]); // The get() method will return the specified HTTP request variable. If the variable does not exist it will return NULL by default. If you would like to set a custom string as the default, provide it as the second argument.

$this->requestType(); // Returns 'PUT', 'POST', 'GET', 'DELETE' depending on HTTP request type

$this->requestType('POST'); // Returns (bool) 

$this->requestType(['POST', 'PUT']); // Returns (bool)  


use ODS\Asset;
use ODS\Ajax;

Asset::addScript(
	array(
		'name'    => 'my_ajax', // It should be the same with Ajax action name.
		'url'     => ODS_PLUGIN_URL . 'assets/js/ajax.js',
		'deps'    => array( 'jquery' ),
		'version' => ODS_VERSION,
		'ajax'    => true,
		'params'  => array(
			'data1' => 'my_data_1',
			'data2' => 'my_data_2',
		),
	),
);

class MyAjax extends Ajax {
	protected $action = 'my_ajax'; // It should be the same with JS name.
	protected function run() {
		
        $nonce = $this->get( 'nonce' );
        $data1 = $this->get( 'data1' );
        $data2 = $this->get( 'data2' );
		
        // Don't forget verify nonce.
        if ( ! wp_verify_nonce( $nonce, 'my_ajax' ) ) {
			$this->JSONResponse( __( 'Invalid', 'my-plugin' ) );
			exit;
		}
		$url     = wp_get_referer();
		$post_id = url_to_postid( $url );
		$my_post = array(
			'ID'         => $post_id,
			'post_title' => 'This is the 123',
		);
		$book_id = wp_update_post( $my_post );
		$this->JSONResponse( $post_id );
	}
}
MyAjax::listen();