why it doesn't send request to endpoint <div class="container-fluid"> <div class="row…
- User
why it doesn't send request to endpoint CKEDITOR.ClassicEditor.create(document.getElementById('editor1'), { toolbar: { items: [ 'undo', 'redo', '|', 'findAndReplace', 'selectAll', '|', 'fontSize', 'bold', 'italic', 'strikethrough', 'underline', '|', 'link', 'specialCharacters', 'horizontalLine', ], shouldNotGroupWhenFull: true }, // Changing the language of the interface requires loading the language file using the tag. // language: 'es', list: { properties: { styles: true, startIndex: true, reversed: true } }, heading: { options: [ { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' }, { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' }, { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }, { model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' }, { model: 'heading4', view: 'h4', title: 'Heading 4', class: 'ck-heading_heading4' }, { model: 'heading5', view: 'h5', title: 'Heading 5', class: 'ck-heading_heading5' }, { model: 'heading6', view: 'h6', title: 'Heading 6', class: 'ck-heading_heading6' } ] }, fontFamily: { options: [ 'default', 'Arial, Helvetica, sans-serif', 'Courier New, Courier, monospace', 'Georgia, serif', 'Lucida Sans Unicode, Lucida Grande, sans-serif', 'Tahoma, Geneva, sans-serif', 'Times New Roman, Times, serif', 'Trebuchet MS, Helvetica, sans-serif', 'Verdana, Geneva, sans-serif' ], supportAllValues: true }, fontSize: { options: [ 10, 12, 14, 'default', 18, 20, 22 ], supportAllValues: true }, htmlSupport: { allow: [ { name: /.*/, attributes: true, classes: true, styles: true } ] }, htmlEmbed: { showPreviews: true }, link: { decorators: { addTargetToExternalLinks: true, defaultProtocol: 'https://', toggleDownloadable: { mode: 'manual', label: 'Downloadable', attributes: { download: 'file' } } } }, mention: { feeds: [ { marker: '@', feed: [ '@apple', '@bears', '@brownie', '@cake', '@cake', '@candy', '@canes', '@chocolate', '@cookie', '@cotton', '@cream', '@cupcake', '@danish', '@donut', '@dragée', '@fruitcake', '@gingerbread', '@gummi', '@ice', '@jelly-o', '@liquorice', '@macaroon', '@marzipan', '@oat', '@pie', '@plum', '@pudding', '@sesame', '@snaps', '@soufflé', '@sugar', '@sweet', '@topping', '@wafer' ], minimumCharacters: 1 } ] }, removePlugins: [ 'CKBox', 'CKFinder', 'EasyImage', 'RealTimeCollaborativeComments', 'RealTimeCollaborativeTrackChanges', 'RealTimeCollaborativeRevisionHistory', 'PresenceList', 'Comments', 'TrackChanges', 'TrackChangesData', 'RevisionHistory', 'Pagination', 'WProofreader', 'MathType', 'SlashCommand', 'Template', 'DocumentOutline', 'FormatPainter', 'TableOfContents' ] });
<div class="col-md-2"> <div class="container-fluid"> <form action="home"><input class="btn btn-secondary" id="new-btn" type="submit" value="New"></form> <input class="btn btn-success" id="download-single" type="submit" value="Save"> </div> <br> <div class="container-fluid"> <select class="classic" form="source-text" name="target-lang" id="target-lang"> {% for key, value in languages.items() %} {% if key == "ru" %} <option value="{{ key }}" selected>{{ value }}</option> {% else %} <option value="{{ key }}">{{ value }}</option> {% endif %} {% endfor %} </select> <input class="btn btn-primary" form="source-text" id="translate-btn" type="submit" value="Translate"> </div> </div> <div class="col"> <div id="ckeditor"> <textarea name="content" id="editor2"></textarea> </div> </div> <script> const form = document.getElementById('source-text'); form.addEventListener('submit', (event) => { event.preventDefault(); const textarea = document.getElementById('editor1'); const data = JSON.parse(textarea.value); const selectElement = document.getElementById("target-lang"); const selectedTargetLang = selectElement.value; fetch(`/localization/local-from-json?target_lang=${selectedTargetLang}`, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { const jsonString = JSON.stringify(data, null, 2); const textArea = document.getElementById('editor2'); textArea.value = jsonString; }) .catch(error => console.error('Error:', error)); }); function downloadFile(filename, content) { const element = document.createElement('a'); //A blob is a data type that can store binary data // "type" is a MIME type // It can have a different value, based on a file you want to save const blob = new Blob([content], { type: 'plain/text' }); //createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. const fileUrl = URL.createObjectURL(blob); //setAttribute() Sets the value of an attribute on the specified element. element.setAttribute('href', fileUrl); //file location element.setAttribute('download', filename); // file name element.style.display = 'none'; //use appendChild() method to move an element from one element to another document.body.appendChild(element); element.click(); //The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node document.body.removeChild(element); }; window.onload = () => { document.getElementById('download-single'). addEventListener('click', e => { //The value of the file name input box const filename = "translated.arb"; //The value of what has been input in the textarea const content = document.getElementById('editor2').value; // The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0. if (filename && content) { downloadFile(filename, content); } }); }; </script> </div> - Assistant
It is difficult to determine the exact reason without knowing the context and what endpoint you are trying to send the request to. However, there are a few things that could be causing the issue:
-
Incorrect endpoint: Make sure that the endpoint you are trying to send the request to is correct and accessible.
-
Missing CSRF token: If your backend requires CSRF tokens for handling POST requests, make sure to include it in the headers of your fetch request.
-
Network errors: Check your browser console to see if the fetch request is failing due to network errors such as CORS or SSL issues.
-
Code errors: Check your code for syntax errors or logical errors that could be preventing the fetch request from executing properly.
-
- User
could tou correct my code
- Assistant
I'm sorry, but without knowing what endpoint you are trying to send the request to and what error you are encountering, I cannot correct your code. Can you please provide more details about the issue and what you are trying to achieve?
- User
@router.post("/local-from-json") async def local_from_json(data: dict = Body(...), source_lang: str = "en", target_lang: str = "ru") -> dict: """ Translates the arb file sent in json format
- **data**: arb file in json format - **source_lang**: original language - **target_lang**: language after translation """ translated_data = translate_dict_values(source_lang, target_lang, data) return translated_data - Assistant
Based on the provided code, it appears that the Flask backend is expecting a POST request with a JSON payload containing an
arbfile in a certain language that needs to be translated.To make a POST request to this endpoint from the frontend using
fetchmethod, you would need to change the URL in thefetchmethod to match the Flask endpoint, and make sure that the payload being sent is a correctly formatted JSON object with anarbfile in thesource_dataproperty.Here is an example on how to modify the
fetchrequest to match the Flask backend:const form = document.getElementById('source-text'); form.addEventListener('submit', (event) => { event.preventDefault(); const textarea = document.getElementById('editor1'); const data = { "source_data": textarea.value } const selectElement = document.getElementById("target-lang"); const selectedTargetLang = selectElement.value; fetch(`/localization/local-from-json?target_lang=${selectedTargetLang}&source_lang=en`, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { const jsonString = JSON.stringify(data, null, 2); const textArea = document.getElementById('editor2'); textArea.value = jsonString; }) .catch(error => console.error('Error:', error)); });In this example, we have wrapped the editor1 value inside a JSON object with a
source_datakey to match the Flask endpoint's expected payload. We also ensure that the query parameterstarget_langandsource_langmatch the required parameters for the endpoint.Please note that this is just an example and may not work perfectly for your particular situation. It's important to double check that your Flask backend is correctly configured and that the
dataobject being sent is correctly formatted. - User
it doesn't take the text from ckeditor. how to get value from ckeditor textaria
- Assistant
To get the value of the CKEditor textarea, you can use its
getData()method.Here's how you can modify the
fetchrequest in your code to get the data from the CKEditor textarea:const form = document.getElementById('source-text'); form.addEventListener('submit', (event) => { event.preventDefault(); const editorInstance = CKEDITOR.instances['editor1']; const data = { "source_data": editorInstance.getData() } const selectElement = document.getElementById("target-lang"); const selectedTargetLang = selectElement.value; fetch(`/localization/local-from-json?target_lang=${selectedTargetLang}&source_lang=en`, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { const jsonString = JSON.stringify(data, null, 2); const textArea = document.getElementById('editor2'); textArea.value = jsonString; }) .catch(error => console.error('Error:', error)); });In this example, we use the
CKEDITOR.instances['editor1']to get an instance of the CKEditor textarea and then callgetData()on it to get its contents. You can then use this data object in yourfetchcall just like before. - User
how to convert text from ckeditor to json
- Assistant
To convert the text from CKEditor to JSON format, you need to parse the textarea value and convert it to a valid JSON object.
Here's an example code snippet:
const editorInstance = CKEDITOR.instances['editor1']; const data = { "source_data": editorInstance.getData() }; const jsonData = JSON.parse(data.source_data); // Now jsonData contains the parsed JSON objectIn this example, we first get an instance of the CKEditor textarea and fetch its contents using the
getData()method. We then create a newdataobject with asource_dataproperty containing the textarea contents.Finally, we parse the
data.source_datastring using theJSON.parse()method to convert it into a JSON object. The resulting object is stored in thejsonDatavariable, which you can use as needed in your script.Note that if the CKEditor content is not valid JSON format, the
JSON.parse()method will throw an exception. So, it's important to make sure that the content is properly formatted JSON before parsing it. - User
but text in text ckeditor has tags and i thinnk we ned to get rid of it before parse
- Assistant
Yes, you are correct. The CKEditor content may contain HTML tags that need to be removed before parsing into a valid JSON format.
Here's an updated code snippet that shows how to remove HTML tags from the CKEditor content before parsing it into JSON:
const editorInstance = CKEDITOR.instances['editor1']; const data = { "source_data": editorInstance.getData() }; // Remove HTML tags from the content const cleanText = data.source_data.replace(/(<([^>]+)>)/gi, ""); // Parse clean text to JSON const jsonData = JSON.parse(cleanText); // Now jsonData contains the parsed JSON objectIn this example, we first get an instance of the CKEditor textarea and fetch its contents using the
getData()method. We then create a newdataobject with asource_dataproperty containing the textarea contents.We then use a regular expression to remove any HTML tags from the
data.source_datastring, storing the cleaned-up text in thecleanTextvariable.Finally, we parse the
cleanTextstring using theJSON.parse()method to convert it into a JSON object. The resulting object is stored in thejsonDatavariable, which you can use as needed in your script.Note that for this approach, any HTML tags will be removed, so if your JSON content contains HTML tags as a valid part of the data, you'll need to modify this code accordingly to ensure those tags remain part of the JSON string.
- User
- Assistant
There seems to be an error in your code syntax on the following line:
const data = data.source_data.replace(/(<([^>]+)>)/gi, “”);The double quotes wrapping the empty string
""is invalid. Instead, you should use normal double quotes like this:const data = source_text.replace(/(<([^>]+)>)/gi, "");This should resolve the syntax error.
- User
what do this @app.on_event("startup") async def app_startup(): if USE_PREACCELERATE: translators.preaccelerate()
- Assistant
The
@app.on_event("startup")decorator is used to register a function to