Skip to content
Advertisement

Converting Javascript data to PHP using ajax in wordpress plugin development

I’m building my first wordpress plugin and I’m having trouble converting a Javascript array of objects into PHP so I can use the data to create individual tables in the wp-admin user area.

Before i actually include the object, i thought i’d try with just a single variable.

Firstly, i included the wp-admin/admin-ajax.php url in wp_localize_script to use in my Javascript file.

function addition_js_script() {
   
    wp_enqueue_script(
        'dynamic-maths-addition-js',
        DYNAMIC_MATHS_URL . 'includes/shortcodes/addition/addition.js',
        ['jquery'],
        time(),
        true 
    );

    wp_localize_script( 'dynamic-maths-addition-js', 'php_data', array(
        'user_addition_skill' => get_user_meta( wp_get_current_user()->ID, 'addition-skill-level', true ),
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    ));

}

if (shortcode_exists( 'addition_quiz' ) ){
    add_action( 'wp_enqueue_scripts', 'addition_js_script', 100 );
    add_action( 'wp_enqueue_scripts', 'addition_css_script', 100 );
}

Then, in addition.js:

jQuery(document).ready(function($){
  let numTest = '75';

jQuery.ajax({
  url: php_data.ajaxurl,
  data: {
    'action': 'php_test',
    'php_test': numTest
  },
  success: function(data){
    console.log('happy');
  }
});

});

Then in my backend menu.php file:

function retrieve_test_number(){
    if (isset($_REQUEST)){
        
         $num = $_REQUEST['php_test'];

        echo 'This is our JS variable: ' . $num;
    }
    die();
}

add_action('wp_ajax_php_test_num', 'retrieve_test_number');

Like this, it displays “This is our JS variable: ” but no number displays.

And even when I try return this function with the variable $num, and i try echo it out in a

tag further down the page, i can’t get the variable to display. Forgive me for any ignorance, my php skills are terrible.

Advertisement

Answer

Change add_action('wp_ajax_php_test_num', 'retrieve_test_number'); to add_action('wp_ajax_php_test', 'retrieve_test_number');. check below code.

HTML

<p id="num"></p>

Javascript

jQuery(document).ready(function($){
    let numTest = '75';
    jQuery.ajax({
        url: php_data.ajaxurl,
        data: {
            'action': 'php_test',
            'php_test': numTest
        },
        success: function(data){
            console.log('happy');
            $('#num').html(data);
        }
    });
});
        

PHP

function retrieve_test_number(){
    if (isset($_REQUEST)){
        $num = $_REQUEST['php_test'];
        echo 'This is our JS variable: ' . $num;
    }
    die();
}
add_action('wp_ajax_php_test', 'retrieve_test_number');
add_action( 'wp_ajax_nopriv_php_test', 'retrieve_test_number' );

Tested and works.

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement