Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: Simple AJAX test 2018-05-22
- Author: Kevin Meredith
- Description: Pluggin to test client site AJAX request
- Version: 1
- */
- // disable direct file access
- if ( ! defined( 'ABSPATH' ) ) {
- exit;
- }
- function load_js() {
- wp_enqueue_script('ajax_test', plugin_dir_url( __FILE__ ) . 'ajax_test.js', array('jquery'), null, true );
- $test_nonce = wp_create_nonce('test_nonce');
- wp_localize_script(
- 'ajax_test',
- 'wbs_ajax_obj',
- array(
- 'ajax_url' => admin_url( 'admin-ajax.php' ),
- 'nonce' => $test_nonce,
- )
- );
- error_log('Load JS TEST SITE');
- // wp_localize_script is used to send an array of php values to javascript
- // it embeds values in the HTML so that be used by java script
- }
- add_action( 'wp_enqueue_scripts', 'load_js' );
- function test_ajax_process_request() {
- error_log('test_ajax_process_request() has been called');
- // first check if data is being sent and that it is the data we want
- //check_ajax_referer( $action, $query_arg, $die )
- if ( check_ajax_referer( 'test_nonce', 'js_nonce', false) ) {
- // 1st parameter is the were the nonce is stored in the $_POST array or what the nonce from field name
- // 2nd parameter is the name of the nonce which is set up in wp_create_nonce()
- // 3rd parameter is die, if true and nonce fails they function will return false
- $ran = rand(0, 100);
- $return_string = 'string from JS: "'.$_POST["from_js"].'" random number from server: '.$ran.' nonce: '.$_POST["js_nonce"].' TEST SITE';
- error_log($return_string);
- echo $return_string;
- die();
- }else{
- $return_string = 'nonce fail (ajax_test.php)';
- echo ($return_string);
- error_log($return_string);
- die();
- }
- }
- add_action('wp_ajax_test_ajax', 'test_ajax_process_request');
- add_action('wp_ajax_nopriv_test_ajax', 'test_ajax_process_request');
- var $ = jQuery.noConflict();
- $( document ).ready(function() {
- console.log('Nonce: '+wbs_ajax_obj.nonce+' from ajax_test.js');
- $.ajax({
- type:"POST",
- url: wbs_ajax_obj.ajax_url, // 'https://lomokev.com/ajaxtest'
- data: {
- action: "test_ajax", // name of the wordpress hook that will trigger function so in this case wp_ajax_nopriv_test_ajax and wp_ajax_test_ajax'
- js_nonce: wbs_ajax_obj.nonce,
- from_js: 'value of from_js from ajax_test.js'
- },
- success:function(data){
- console.log(data);
- },
- error: function(errorThrown){
- console.log(Object.values(errorThrown));
- }
- });
- // if it's a 404 the error says "error"
- // but this says "Bad Request"
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement