Retrieve the image description using the file_picker_callback and image uploader in Tinymce

TL:DR I am attempting to retrieve the value of the image_description field using JavaScript to include it in my post XHR request

Original query:

I am utilizing the file_picker_callback type image

I have enabled the image_description input field in my

tinymce.init({
     ....,
     image_description: true,
     ...

Everything is uploading correctly, but I want to send the image_description field to store in the DB as well. However, I am having difficulty retrieving the data

Below are the two functions, directly from the tinymce website:

  file_picker_callback: function(cb, value, meta) {

    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');

    input.onchange = function() {
      console.log(this.files);
      var file = this.files[0];

      console.log( meta ); //I thought it might be here in the meta bt it isn't

     console.log( $('#mceu_62').val() ); //I tried to get it from its id but it returns undefined i think that field is created after this function is created.



      var id = file.name;
      var blobCache = tinymce.activeEditor.editorUpload.blobCache;
      var blobInfo = blobCache.create(id, file);
      blobCache.add(blobInfo);


      // call the callback and populate the Title field with the file name
      cb(blobInfo.blobUri(), { title: file.name });
    };

    input.click();
  },
  images_upload_handler: function (blobInfo, success, failure) {
      var xhr, formData;

      xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open('POST', '/articles/postAcceptor');

      xhr.onload = function() {
        var json;

        if (xhr.status != 200) {
          failure('HTTP Error: ' + xhr.status);
          return;
        }

        json = JSON.parse(xhr.responseText);

        if (!json || typeof json.location != 'string') {
          failure('Invalid JSON: ' + xhr.responseText);
          return;
        }

        success(json.location);
      };

      formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      formData.append('description', /*but i can't get the value*/);

      xhr.send(formData);
    }

@Karl Morrisons

Answer №1

Follow this method to retrieve the value:

image_uploader: function (blobInfo, success, failure) {
      var http, formData;

      http = new XMLHttpRequest();
      http.withCredentials = false;
      http.open('POST', '/articles/acceptImage');

      http.onload = function() {
        var jsonData;

        if (http.status != 200) {
          failure('HTTP Error: ' + http.status);
          return;
        }

        jsonData = JSON.parse(http.responseText);

        if (!jsonData || typeof jsonData.source != 'string') {
          failure('Invalid JSON: ' + http.responseText);
          return;
        }

        success(jsonData.source);
      };


      var info = '';

      jQuery(tinymce.activeEditor.dom.getRoot()).find('img').not('.processed').each(
    function() {
        info = $(this).attr("alt");
        $(this).addClass('processed');
    });

      formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      formData.append('description', info);

      http.send(formData);
    }

Answer №2

Maybe this can help you out:

<!DOCTYPE html>
<html>
<head>
<script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
<script>tinymce.init({ selector:'textarea' });</script>
</head>
<body>
<textarea>You can also obtain a free TinyMCE Cloud API key!</textarea>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The webpage encountered an issue while trying to load a resource: the server returned a 500 (Internal Server Error) status message, preventing the submission of the data

When I use AJAX jQuery to send data via POST, the input name does not get sent and the database shows NULL as the answer. Thank you for any assistance. Below is my JQuery code: $('#btn-save').click(function(){ $.ajax({ url: "<? ...

Accessing a parent class constructor object in NodeJS from the Child Class

I'm currently working on creating a Controller Class that will handle the initialization of all my routes using ExpressJS. Below is a simple example of what I have so far: class Test extends Controller { constructor(App) { const Routes = [ ...

Leveraging the power of Bootstrap and JavaScript to implement a custom Toast feature

I am utilizing Bootstrap 4 to design Toasts, and I am presently developing a JavaScript function to generate a toast. My attempt to create elements within the JS file did not properly style it. index.html <!doctype html> <html lang="en"> ...

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...

Just starting out with JS/jQuery and having trouble hiding a div as I thought it should (or revealing it incorrectly)

The issue can be observed by visiting . Upon clicking on a location name, a home "button" appears in the bottom left corner. Clicking this home button is supposed to revert back to the original page layout and hide the button. However, as soon as the curso ...

Checking for the existence of data in a MySQL table using Node.js resulted in an error message: "TypeError: res.send is

I am currently attempting to verify the existence of data in a mysql table. Upon doing so, I encountered an error indicating TypeError: res.send is not a function. The mysql table contains ample data with three columns, each specified as varchar(45), alon ...

Is jQuery capable of appropriately escaping my quotes?

Currently, I am utilizing $.cookie() to retrieve all the values from a cookie which are stored in JSON format: var properties = $.cookie('params'); The output of properties is: {"distinct_id": "13f97d6600b42e-000e6293c-6b1b2e75-232800-13f97d66 ...

JavaScript can be used to target and remove parent <tr> elements that contain empty <td> elements with a specific class

I am facing a challenge with a large HTML table that is populated by variables set in JavaScript from my database response. When the database returns an empty string, I want to remove the entire parent row using JavaScript. Although I have attempted to us ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

The server nodejs is unable to recognize the dotenv file

This is my very first project with the MERN stack and I'm currently working on pushing it to GitHub. Since I am using Mongoose, I needed to protect the login credentials for my account. After some research, I discovered the solution of using a .env fi ...

Angular controller fails to fetch scope variable in subsequent view

I'm currently working on implementing a login feature that directs a validated user to a personalized HTML view that greets them with their name. The initial view is a login page. When the user clicks the "Log In" button, the ng-click function is sup ...

A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view? The orderBy filter only sorts one level, but I need it to sort recursively for all children. Input: R2 -->S4 ------>T5 ------> ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

encountered empty values when retrieving static paths

I need to retrieve the values of slug and tags in my params. It's important to note that tags is not an array, but just a string. export async function getStaticPaths() { const chapters = await client.fetch( `*[_type == "chapters" & ...

Click on the dropdown item in the Bootstrap btn-group dropdown

I am interested in clicking the dropdown item within the btn-group and triggering an alert message. This is the HTML code I have: <td> <div class="btn-group" role="group"> <button id="btnGroupVerticalDrop2" type="button" class= ...

Organize data by multiple criteria using List.js

Attempting to configure the list.js plugin to allow sorting based on multiple values. Specifically, the goal is to sort by category first and then alphabetically by title within each category. See a demo here: http://jsfiddle.net/8E7cH/ This functional ...

Working with JSON data in AngularJS: A guide to loading data onto a scope variable

I am in the process of developing my personal website where I want to be able to update content easily without having to mess with the HTML code. My approach involves loading and updating a JSON file to achieve this, however, I am currently struggling with ...

Removing items dynamically from a list created using ng-repeat

I have an array of nested JSON objects and I am using ng-repeat to create a list with the nested arrays. My goal is to dynamically delete items from this list upon button click by calling a function in the controller: $scope.remove= function(path){ va ...

How to Query MongoDB and reference an object's properties

I'm trying to execute a script on my MongoDB that will set teacher_ids[] = [document.owner_id]. The field owner_id already exists in all the objects in the collection. Here is my current attempt: db.getCollection('readings').update({ $where ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...