Skip to content

Instantly share code, notes, and snippets.

@rdennler
Forked from franz-josef-kaiser/ajax.js
Created July 25, 2016 19:22
Show Gist options
  • Select an option

  • Save rdennler/ecca9f08f6c7b8c1a01c8411584722e3 to your computer and use it in GitHub Desktop.

Select an option

Save rdennler/ecca9f08f6c7b8c1a01c8411584722e3 to your computer and use it in GitHub Desktop.

Revisions

  1. @franz-josef-kaiser franz-josef-kaiser revised this gist Mar 5, 2014. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions wpajax.php
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    <?php
    defined( 'ABSPATH' ) or exit;
    /** Plugin Name: (WCM) AJAX Example Plugin */

    add_action( 'plugins_loaded', array( 'PoorMansNameSpaceAJAX', 'getInstance' ) );
    class PoorMansNameSpaceAJAX
    @@ -32,14 +32,14 @@ public function __construct()

    public function scriptsRegister( $page )
    {
    $file = 'YourAJAXHandlingFile.js';
    $file = 'ajax.js';
    wp_register_script(
    $this->name,
    plugins_url( "assets/scripts/{$file}", __FILE__ ),
    plugins_url( $file, __FILE__ ),
    array(
    'jquery',
    ),
    filemtime( plugin_dir_path( __FILE__ )."assets/scripts/{$file}" ),
    filemtime( plugin_dir_path( __FILE__ )."/{$file}" ),
    true
    );
    }
  2. @franz-josef-kaiser franz-josef-kaiser revised this gist Feb 19, 2014. 1 changed file with 2 additions and 6 deletions.
    8 changes: 2 additions & 6 deletions wpajax.php
    Original file line number Diff line number Diff line change
    @@ -72,16 +72,12 @@ public function ajaxCb( $data )
    {
    $data = array_map( 'esc_attr', $_GET );

    check_ajax_referer( $data['action'] );
    ! check_ajax_referer( $data['action'], "_ajax_nonce", false )
    AND wp_send_json_error();

    # @TODO Handle processing of data in here
    # @TODO Validate data with absint(), esc_*(), etc.

    # @TODO Check if we got an error and if so, send it
    # @example #1)
    ! wp_verify_nonce( $this->nonce, "{$this->name}_action" )
    AND wp_send_json_error();

    # @example #2)
    if ( ! $data['foo'] )
    wp_send_json_error();
  3. @franz-josef-kaiser franz-josef-kaiser revised this gist Oct 10, 2013. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion ajax.js
    Original file line number Diff line number Diff line change
    @@ -34,14 +34,15 @@
    action : plugin.action,
    _ajax_nonce : plugin._ajax_nonce,
    // WordPress JS-global
    // Only set in admin
    postType : typenow,
    },
    beforeSend : function( d ) {
    console.log( 'Before send', d );
    }
    } )
    .done( function( response, textStatus, jqXHR ) {
    console.log( 'AJAX done', data, textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
    console.log( 'AJAX done', textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
    } )
    .fail( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
  4. @franz-josef-kaiser franz-josef-kaiser revised this gist Oct 10, 2013. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion wpajax.php
    Original file line number Diff line number Diff line change
    @@ -80,7 +80,8 @@ public function ajaxCb( $data )
    # @TODO Check if we got an error and if so, send it
    # @example #1)
    ! wp_verify_nonce( $this->nonce, "{$this->name}_action" )
    AND wp_send_json_error()
    AND wp_send_json_error();

    # @example #2)
    if ( ! $data['foo'] )
    wp_send_json_error();
  5. @franz-josef-kaiser franz-josef-kaiser revised this gist Oct 10, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion wpajax.php
    Original file line number Diff line number Diff line change
    @@ -54,7 +54,7 @@ public function scriptsLocalize( $page )
    $this->nonce = wp_create_nonce( "{$this->name}_action" );
    wp_localize_script( $this->name, "{$this->name}Object", array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    '_ajax_nonce' => $nonce,
    '_ajax_nonce' => $this->nonce,
    'action' => "{$this->name}_action",
    'post_type' => get_current_screen()->post_type,
    # etc.
  6. @franz-josef-kaiser franz-josef-kaiser revised this gist Oct 10, 2013. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions wpajax.php
    Original file line number Diff line number Diff line change
    @@ -19,6 +19,7 @@ public static function getInstance()
    public function __construct()
    {
    add_action( 'wp_loaded', array( $this, 'scriptsRegister' ) );
    # Could as well be: wp_enqueue_scripts or login_enqueue_scripts
    add_action( 'admin_enqueue_scripts', array( $this, 'scriptsEnqueue' ) );

    # Logged in users:
  7. @franz-josef-kaiser franz-josef-kaiser revised this gist Oct 9, 2013. 1 changed file with 45 additions and 45 deletions.
    90 changes: 45 additions & 45 deletions ajax.js
    Original file line number Diff line number Diff line change
    @@ -1,52 +1,52 @@
    ( function( $, plugin ) {
    "use strict";
    "use strict";

    // Working with promises to bubble event later than core.
    $.when( someObjectWithEvents ).done( function() {
    console.log( 'AJAX request done.' );
    } )
    .then( function() {
    setTimeout( function() {
    console.log( 'AJAX requests resolved.' );
    }, 500 );
    } );
    // Working with promises to bubble event later than core.
    $.when( someObjectWithEvents ).done( function() {
    console.log( 'AJAX request done.' );
    } )
    .then( function() {
    setTimeout( function() {
    console.log( 'AJAX requests resolved.' );
    }, 500 );
    } );

    // Same as above, but happens as onClick Action
    $( '#form-button' ).on( 'click', function() {
    // Debug: return; here if we need to debug/var_dump the save_post callback in PHP.
    // return;
    // Same as above, but happens as onClick Action
    $( '#form-button' ).on( 'click', function() {
    // Debug: return; here if we need to debug/var_dump the save_post callback in PHP.
    // return;

    // Working with promises to bubble event later than core.
    $.when( someObjectWithEvents ).done( function() {
    setTimeout( function() {
    console.log( 'AJAX requests done. Happened after onClick event.' );
    }, 2000 );
    } );
    // One can happily use .then() here as well.
    // Working with promises to bubble event later than core.
    $.when( someObjectWithEvents ).done( function() {
    setTimeout( function() {
    console.log( 'AJAX requests done. Happened after onClick event.' );
    }, 2000 );
    } );
    // One can happily use .then() here as well.
    } );

    // Alternate solution: jQuery.ajax()
    // One can use $.post(), $.getJSON() as well
    // I prefer defered loading & promises as shown above
    $.ajax( {
    url : plugin.ajaxurl,
    data : {
    action : plugin.action,
    _ajax_nonce : plugin._ajax_nonce,
    // WordPress JS-global
    postType : typenow,
    },
    beforeSend : function( d ) {
    console.log( 'Before send', d );
    }
    } )
    .done( function( response, textStatus, jqXHR ) {
    console.log( 'AJAX done', data, textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
    } )
    .fail( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
    } )
    .then( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
    } );
    // Alternate solution: jQuery.ajax()
    // One can use $.post(), $.getJSON() as well
    // I prefer defered loading & promises as shown above
    $.ajax( {
    url : plugin.ajaxurl,
    data : {
    action : plugin.action,
    _ajax_nonce : plugin._ajax_nonce,
    // WordPress JS-global
    postType : typenow,
    },
    beforeSend : function( d ) {
    console.log( 'Before send', d );
    }
    } )
    .done( function( response, textStatus, jqXHR ) {
    console.log( 'AJAX done', data, textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
    } )
    .fail( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
    } )
    .then( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
    } );
    } )( jQuery, ajaxexampleObject || {} );
  8. @franz-josef-kaiser franz-josef-kaiser revised this gist Oct 9, 2013. 2 changed files with 18 additions and 11 deletions.
    9 changes: 5 additions & 4 deletions ajax.js
    Original file line number Diff line number Diff line change
    @@ -11,6 +11,7 @@
    }, 500 );
    } );

    // Same as above, but happens as onClick Action
    $( '#form-button' ).on( 'click', function() {
    // Debug: return; here if we need to debug/var_dump the save_post callback in PHP.
    // return;
    @@ -24,10 +25,10 @@
    // One can happily use .then() here as well.
    } );

    // Alaternate solution: jQuery.ajax()
    // One can use $.post(), $.getJSON() as well
    // I prefer defered loading & promises
    $.ajax( {
    // Alternate solution: jQuery.ajax()
    // One can use $.post(), $.getJSON() as well
    // I prefer defered loading & promises as shown above
    $.ajax( {
    url : plugin.ajaxurl,
    data : {
    action : plugin.action,
    20 changes: 13 additions & 7 deletions wpajax.php
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,8 @@ class PoorMansNameSpaceAJAX
    {
    public static $instance = null;

    public $nonce = '';

    public $name = 'ajaxexample';

    public static function getInstance()
    @@ -48,9 +50,10 @@ public function scriptsEnqueue( $page )

    public function scriptsLocalize( $page )
    {
    $this->nonce = wp_create_nonce( "{$this->name}_action" );
    wp_localize_script( $this->name, "{$this->name}Object", array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    '_ajax_nonce' => wp_create_nonce( "{$this->name}_action" ),
    '_ajax_nonce' => $nonce,
    'action' => "{$this->name}_action",
    'post_type' => get_current_screen()->post_type,
    # etc.
    @@ -70,13 +73,16 @@ public function ajaxCb( $data )

    check_ajax_referer( $data['action'] );

    # @TODO Handle processing of data in here
    # @TODO Validate data with absint(), esc_*(), etc.
    # @TODO Handle processing of data in here
    # @TODO Validate data with absint(), esc_*(), etc.

    # @TODO Check if we got an error and if so, send it
    # @example ! wp_verify_nonce( ... ) AND wp_send_json_error()
    if ( ! $data['foo'] )
    wp_send_json_error();
    # @TODO Check if we got an error and if so, send it
    # @example #1)
    ! wp_verify_nonce( $this->nonce, "{$this->name}_action" )
    AND wp_send_json_error()
    # @example #2)
    if ( ! $data['foo'] )
    wp_send_json_error();

    wp_send_json_success( array(
    #'foo' => 'bar',
  9. @franz-josef-kaiser franz-josef-kaiser created this gist Oct 9, 2013.
    51 changes: 51 additions & 0 deletions ajax.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    ( function( $, plugin ) {
    "use strict";

    // Working with promises to bubble event later than core.
    $.when( someObjectWithEvents ).done( function() {
    console.log( 'AJAX request done.' );
    } )
    .then( function() {
    setTimeout( function() {
    console.log( 'AJAX requests resolved.' );
    }, 500 );
    } );

    $( '#form-button' ).on( 'click', function() {
    // Debug: return; here if we need to debug/var_dump the save_post callback in PHP.
    // return;

    // Working with promises to bubble event later than core.
    $.when( someObjectWithEvents ).done( function() {
    setTimeout( function() {
    console.log( 'AJAX requests done. Happened after onClick event.' );
    }, 2000 );
    } );
    // One can happily use .then() here as well.
    } );

    // Alaternate solution: jQuery.ajax()
    // One can use $.post(), $.getJSON() as well
    // I prefer defered loading & promises
    $.ajax( {
    url : plugin.ajaxurl,
    data : {
    action : plugin.action,
    _ajax_nonce : plugin._ajax_nonce,
    // WordPress JS-global
    postType : typenow,
    },
    beforeSend : function( d ) {
    console.log( 'Before send', d );
    }
    } )
    .done( function( response, textStatus, jqXHR ) {
    console.log( 'AJAX done', data, textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
    } )
    .fail( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
    } )
    .then( function( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
    } );
    } )( jQuery, ajaxexampleObject || {} );
    85 changes: 85 additions & 0 deletions wpajax.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@
    <?php
    defined( 'ABSPATH' ) or exit;

    add_action( 'plugins_loaded', array( 'PoorMansNameSpaceAJAX', 'getInstance' ) );
    class PoorMansNameSpaceAJAX
    {
    public static $instance = null;

    public $name = 'ajaxexample';

    public static function getInstance()
    {
    null === self::$instance AND self::$instance = new self;
    return self::$instance;
    }

    public function __construct()
    {
    add_action( 'wp_loaded', array( $this, 'scriptsRegister' ) );
    add_action( 'admin_enqueue_scripts', array( $this, 'scriptsEnqueue' ) );

    # Logged in users:
    # add_action( "wp_ajax_{$this->name}_action", array( $this, 'ajaxCb' ) );
    # Guests:
    add_action( "wp_ajax_nopriv_{$this->name}_action", array( $this, 'ajaxCb' ) );

    add_action( 'admin_enqueue_scripts', array( $this, 'scriptsLocalize' ) );
    }

    public function scriptsRegister( $page )
    {
    $file = 'YourAJAXHandlingFile.js';
    wp_register_script(
    $this->name,
    plugins_url( "assets/scripts/{$file}", __FILE__ ),
    array(
    'jquery',
    ),
    filemtime( plugin_dir_path( __FILE__ )."assets/scripts/{$file}" ),
    true
    );
    }

    public function scriptsEnqueue( $page )
    {
    wp_enqueue_script( $this->name );
    }

    public function scriptsLocalize( $page )
    {
    wp_localize_script( $this->name, "{$this->name}Object", array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    '_ajax_nonce' => wp_create_nonce( "{$this->name}_action" ),
    'action' => "{$this->name}_action",
    'post_type' => get_current_screen()->post_type,
    # etc.
    ) );
    }

    public function renderForm()
    {
    wp_nonce_field( "{$this->name}_action", $this->name );
    # @TODO Build form
    # @TODO Hook somewhere
    }

    public function ajaxCb( $data )
    {
    $data = array_map( 'esc_attr', $_GET );

    check_ajax_referer( $data['action'] );

    # @TODO Handle processing of data in here
    # @TODO Validate data with absint(), esc_*(), etc.

    # @TODO Check if we got an error and if so, send it
    # @example ! wp_verify_nonce( ... ) AND wp_send_json_error()
    if ( ! $data['foo'] )
    wp_send_json_error();

    wp_send_json_success( array(
    #'foo' => 'bar',
    ) );
    }
    }