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.

JavaScript

Then, in addition.js:

JavaScript

Then in my backend menu.php file:

JavaScript

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

JavaScript

Javascript

JavaScript

PHP

JavaScript

Tested and works.

enter image description here

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