


Master the content library of rich text editors: the collaborative practice of JavaScript and PHP
Aug 04, 2025 pm 06:57 PMWhen creating content using rich text editors such as TinyMCE or CKEditor, a common problem is that when a user submits a form, all HTML formats are lost in the database, leaving only plain text. This is usually not because the HTML tag is stripped, but because the front-end script fails to properly get the full HTML content generated by the rich text editor when collecting form data.
Problem analysis
In the original code, JavaScript uses $('#dataForm').serializeArray() to serialize form data. This method is usually effective for standard or
Solution: Front-end JavaScript processing
To solve this problem, we need to manually get its current HTML content from the rich text editor instance before submitting the form and add it to the data to be submitted. TinyMCE provides an API method tinymce.activeEditor.getContent() to get the editor's complete HTML content.
The following is a modified JavaScript code example:
// Make sure the TinyMCE editor has been initialized correctly tinymce.init({ selector: 'textarea.tinymce', // Make sure the selector matches the textarea in HTML plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste code help wordcount', toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help' // ... other TinyMCE configurations}); //Bind form submission event $('#dataBtn').click(function(e){ e.preventDefault(); // Block the default submission behavior of the form to manually submit it through AJAX // 1. Get the complete HTML content of the TinyMCE editor // tinymce.activeEditor Points to the currently activated editor instance var myContent = tinymce.activeEditor.getContent(); // 2. Serialize other data of the form const data = $('#dataForm').serializeArray(); // 3. Add the content of TinyMCE to the serialized data array // Make sure that the 'name' attribute is consistent with the variable name (such as $_POST['details']) received by the backend PHP data.push({name: 'details', value: myContent}); // 4. Use AJAX to send data to the backend $.post( $('#dataForm').attr('action'), // Get the form's action attribute as the request URL data, // Send complete data containing rich text content function(result) { // Process the result $('#dataResult').html(result); } ); });
Code explanation:
- e.preventDefault(): This is a very important step, which prevents the browser's default form submission behavior. Without this line, the form will be submitted immediately when the Submit button is clicked, and our AJAX request may not have time to send, or may result in duplicate submissions.
- tinymce.activeEditor.getContent(): This is the correct way to get the current HTML content of the TinyMCE editor. It returns an HTML string containing all formats and tags.
- $('#dataForm').serializeArray(): Still used to get data for other non-rich text fields in the form.
- data.push({name: 'details', value: myContent}): Adds the HTML content obtained from TinyMCE as a new key-value pair to the data array generated by serializeArray(). Here name: 'details' must be consistent with the $_POST key name expected to be received in the backend PHP script.
Backend PHP processing and security considerations
In the PHP backend, once the frontend correctly sends a request containing HTML content, the way of receiving data is similar to processing a normal text field. However, since it is received by the user input HTML content, security is the primary concern.
<?php // Assume $db is your database operation class or connection object // Introduce database connection and class (based on your project structure) // require_once 'path/to/database_class.php'; // $db = new Database(); // Example $details = ''; // Initialize the variable// Check if $_POST['details'] exists and get the content if (isset($_POST['details'])) { $details = $_POST['details']; } $flag = false; $error = []; $valid = []; if (!empty($details)) { $flag = true; } else { $error[] = "Please provide details!"; $flag = false; } if ($flag == true) { // **Important: Secure processing must be done before inserting user input into the database! ** // 1. SQL injection protection: Use prepared statements (Prepared Statements) // This is the most recommended way to prevent SQL injection. // The example uses PDO, if you use MySQLi, the principle is similar. try { // Assume $pdo is your PDO database connection object// $stmt = $pdo->prepare("INSERT INTO tbl_post(details) VALUES (?)"); // $stmt->execute([$details]); // If you are using a custom database class, make sure it uses preprocessing statements or appropriate escape functions internally // For example, if $db->insert() is not processed internally, you need to handle it manually // $details_escaped = $db->escape($details); // Assume that your database class has escape method // $query = "INSERT INTO tbl_post(details)VALUES('$details_escaped')"; // Assume that the preprocessing statement or safe escape of $query = "INSERT INTO tbl_post(details)VALUES(?)"; // Use the placeholder $result = $db->insert($query, [$details]); // Assume that the insert method supports the preprocessing parameter if ($result) { $valid[] = "Data added successfully!"; } else { $error[] = "The operation failed, please try again later!"; } } catch (PDOException $e) { $error[] = "Database operation error: ". $e->getMessage(); } } else { $error[] = "An unknown error occurred!"; } // Output result (usually in JSON format for front-end AJAX processing) if (!empty($valid)) { echo json_encode(['status' => 'success', 'message' => implode(', ', $valid)]); } else { echo json_encode(['status' => 'error', 'message' => implode(', ', $error)]); } ?>
Safety precautions:
- SQL Injection Prevention:
- Prepared Statements are highly recommended : This is a best practice to prevent SQL injection. It separates SQL query logic from data, ensuring that user input is not interpreted as SQL commands. Whether using PDO or MySQLi, this approach should be preferred.
- Avoid splicing of user input directly into SQL query strings. If you have to splice (not recommended), use database-specific escape functions (such as mysqli_real_escape_string()), but this is not as safe as preprocessing statements.
- Cross-site scripting attack (XSS Prevention):
- When the HTML content entered by the user is stored into the database, its original format is usually retained. However, XSS protection is required when taking these contents out of the database and displaying them on a web page .
- Filter or Purify HTML (HTML Sanitization) : Use specialized libraries (such as HTML Purifier for PHP) to filter out potential malicious HTML tags and attributes (such as <script> tags, onerror events, etc.). This ensures that only secure HTML tags are rendered, preventing attackers from injecting malicious scripts.</script>
- Never output the HTML entered by the user directly : unless you are sure that it has been strictly purified.
Database field type selection
Content generated by rich text editors usually contains a large amount of HTML tags and text, which can result in longer content lengths. Therefore, when designing database tables, you should choose a field type that can store long text:
- MySQL:
- TEXT: Store up to 65,535 characters.
- MEDIUMTEXT: Store up to 16,777,215 characters.
- LONGTEXT: Store up to 4,294,967,295 characters (4GB). Choose the right type according to the expected length of the content, usually TEXT or MEDIUMTEXT is sufficient to meet most of the needs.
Summarize
To properly insert HTML content from rich text editors such as TinyMCE into the database, the key is how front-end JavaScript accurately gets the editor's content and sends it to the server. The complete HTML string can be obtained through the tinymce.activeEditor.getContent() method. When processing backend PHP, in addition to receiving data, it is more important to strictly implement SQL injection protection (using preprocessing statements) and XSS attack prevention (purifying HTML when displayed) to ensure the security of the application. Correct front-end collaboration and rigorous security measures are the basis for building robust web applications.
The above is the detailed content of Master the content library of rich text editors: the collaborative practice of JavaScript and PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
