Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


30,548 Points

PHP function into JS File using AJAX (Wordpress plugin environment)

I am creating a tinyMCE button for the wp WYSIWYG editor. Basically what happens is when a use clicks on the button a modal form pops up and they have to enter a few fields. However One of the fields needs to be a list box that lists every post category and the user will select one. The basic syntax for that is as follows:

type: 'listbox', 
name: 'sds-category', 
label: 'Category', 
'values': [
    {text: 'Name Of Cat', value: 'Cat ID'},
    {text: 'Name Of Cat', value: 'Cat ID'},
    {text: 'Name Of Cat', value: 'Cat ID'}

So in order to get all the categories displaying like that I have used a PHPfunction which will spit out that {text: '', value: ''} syntax for every category and it goes as follows:

function write_cat_list($cat){
    $cats = get_categories('hide_empty=false&orderby=name&order=ASC&parent=' . $cat);

    if($cats) :
        foreach ($cats as $cat) :
            $tinyMCE_list[] = "{text: '".$cat->name."', value: '".$cat->term_id."'}";
        echo implode(',', $tinyMCE_list);

So now all that is left is placing the PHP function "write_cat_list(0)" into my .js file, and that is where I am completely stuck!

I am not sure how to go about doing this, because I am very very inexperienced with AJAX, is there an easy way or a jquery function that will make it easy to include my php function to this js file?

1 Answer