Giter VIP home page Giter VIP logo

wp_ajax's Introduction

WP_AJAX

Simple Controllers for WordPress

WP_AJAX is a class for interfacing with WordPress’s built in AJAX system. This class is designed to fully abstract the developer from the traditional hook based system to a clean controller style structure. Simply define the class, echo urls with url($params = []) method and write what code you want to execute in the run() method.

Introduction: Medium Post

Class ExampleAction extends WP_AJAX{

    protected $action = 'example-action';

    protected function run(){

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

    }
}
ExampleAction::listen();

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

ExampleAction.php

Font-end

<a href="<?= ExampleAction::url(['name' => 'Anthony Budd']) ?>" >This is a link</a>

Page-Template.php

Or

$('.submit-btn').click(function(){

    $.post('http://example.com/wp-admin/admin-ajax.php',{
        action: 'example-action',
        name: $('.name-field').val(),
    },function(data){
        console.log(data)
    }, 'JSON');
    
});

script.js

Installation

Require WP_AJAX with composer

$ composer require anthonybudd/wp_ajax

Or

Download the WP_AJAX class and require it at the top of your functions.php file.

    require 'src/WP_AJAX.php';

Setup

You will need to create a new class that extends WP_AJAX. This class must have one protected property called $action and one protected method named run(). $action will be the AJAX action name See wp_ajax_(action).

Class Example extends WP_AJAX
{
    protected $action = 'example';

    protected function run(){
        echo "Success!";
    }
}

Listen

Next you have to call the static method listen(). This will create all of the hooks so WordPress knows to call the run() method when the correct AJAX endpoint is hit. Note: You will need to call the listen() method for each of your AJAX actions.

ExampleAJAX::listen();

If you would like to only allow signed in users to access your AJAX endpoint add the argument FALSE to the listen method.

ExampleAJAX::listen(FALSE);

JSON Response

If you want to respond to an AJAX request with data the JSONResponse() method will automatically set the content type header to ‘application/json’ and JSON encode the data provided to the method.

I am aware that WordPress has a function called wp_send_json() but, due to the fact that I know how much it annoys WP developers that I have included this method, I will not be removing it.

Class ExampleAJAX extends WP_AJAX{
    ..

    protected function run(){
        $post5 = get_post(5);

        $this->JSONResponse($post5);
    }
}

Helper Methods

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)  

Example

Class CreatePost extends WP_AJAX
{
    protected $action = 'create_post';

    protected function run(){
        if($this->isLoggedIn()){
            $post = [
                'post_status' => 'publish'
            ];
            
            if( $this->requestType(['POST', 'put']) ){
                $post['post_content'] = 'This request was either POST or PUT';
            }else if( $this->requestType('get') ){
                $post['post_content'] = 'This request was GET';
            }

            $post['post_title'] = sprintf('This post was created by %s', $this->user->data->user_nicename);
            
            wp_insert_post($post);

            $this->JSONResponse($post);
        }
    }
}

CreatePost::listen();

// http://example.com/wp-admin/admin-ajax.php?action=create_post

wp_ajax's People

Contributors

anthonybudd avatar thekhorshed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

wp_ajax's Issues

Undefined: is_user_logged_in()

I'm getting that as an error and, it seems that it's because is_user_logged_in() is a pluggable function. And since I'm using WP_AJAX in a plugin I'm working on, it fails because it can't find the function because it's called too soon in the WP workflow.

I don't know what a decent solution would be to be honest, and that's why I didn't make a pull request. At first I though to make a protected $isPlugin = false by default, and then overwrite it on demand that would use different method in isLoggedIn(), but I'm not sure what would be the different method.

At this moment, this is how I modified the file. It's not perfect, but it works.

public function isLoggedIn()
    {
        if (function_exists('is_user_logged_in')) {
            return is_user_logged_in();
        }

        return null;
    }

What would you do?

PHP Warning!

Hi there, great job on this AJAX class.

Here is the Error I'm getting:

PHP Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Test::boot() should not be called statically in /wp/wp-includes/class-wp-hook.php on line 298

The boot method should be static?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.