Home > Blockchain >  Using ajax call to generate array for link_list for tinymce
Using ajax call to generate array for link_list for tinymce

Time:12-06

I'm trying to create a link_list in TinyMCE (version 6) using an AJAX call (not sure if this is the right way, but I'm trying to update old code). The backend is handled with Flask, which gets a tuple of dictionaries from the database where the title and value of each link are key-value pairs. I believe what I need to do is find a way to make the ajax call return the correct type of array, e.g.

my_ary=[
    { title: 'title 1',value: 'link1'},
    { title: 'title 2',value: 'link2'},
    { title: 'title 3',value: 'link3'},
]

Is this possible? Or am I heading in a completely incorrect direction? This is what I currently have-

tinyMCE intialization:

tinymce.init({
    selector: '.my_editor',
    plugins: ['link'],
    toolbar: 'link',
    link_list: (success) => {
        const links = update_item_list();
        success(links);
    },
});

javascript containing ajax call:

function update_item_list()
{
    my_link_list = $.ajax({
        async: false,
        type: "POST",
        url: "ajax_endpoint",
        data: {},
        cache: false,
        dataType: "json",
        success: function(list)
        {
        const my_ary=Array.from(Array(list.length), () => ({ title: '', value: '' }))
        for(var i = 0; i < list.length; i  )
            {
            my_ary[i].title=list[i].title;
            my_ary[i].value=list[i].value;
            }
        },
        error: function(html, status)
        {
            alert("error: "   status);
        }
    });
    return my_link_list;
}

flask endpoint:

@my_project.route('/ajax_endpoint',methods=['POST'])
def ajax_endpoint():
    uploaded_items = ["{"   ", ".join([f"""'{key}': '{item.get(key)}'""" for key in item.keys()])   "}" for item in get_link_items()]
    html = "["   ", ".join(uploaded_items)   "]"

    return jsonify(html)

CodePudding user response:

I figured out a solution without using ajax. Per tinyMCE's documentation for link_list, one can use a URL which returns JSON data. To accomplish this, I created a list of dictionaries with keys of "title" and "value" for each link, and then used jsonify when returning the list. Now, this is what my code looks like-

tinyMCE intialization:

tinymce.init({
    selector: '.my_editor',
    plugins: ['link'],
    toolbar: 'link',
    link_list: "ajax_endpoint"
    },
});

flask endpoint:

@my_project.route('/ajax_endpoint',methods=['POST'])
def ajax_endpoint():
    html = [{"title": item.get('title'), "value": item.get('value')} for item in get_link_items()]
    return jsonify(html)
  • Related