Using jQuery to retrieve the content of a textarea and display it

I need help finding the right way to read and write to a Linux text file using JavaScript, jQuery, and PHP. Specifically, I want to retrieve the value from a textarea (#taFile) with jQuery ($("#taFile").val();) and send it via $.post to a PHP script that will then write the value to a text file.

Although my code is mostly functional, I have encountered an issue: when sending the textarea value via $.post, all special characters are disappearing. More specifically, 1) all special characters vanish, 2) new lines are turned into spaces, and 3) everything after certain special characters (like #) is lost.

These scripts are still in progress, so I am open to any suggestions or improvements!

Javascript:

$(document).ready(function() {
 $("input:button").button();
 $("#tabs").tabs();

 $("#tabs").tabs({
  select: function(event, ui) { // When a tab is selected
   file = ui.panel.id;
   console.log("js: file: "+file);
   if (file == "items" || file == "groups" || file == "whitelist" || file == "users"){ // if file is valid
    $("#taFile").remove(); // Remove any old textareas
    $("#"+file).html(''); // Add a new textarea
    $.post("/php/getFile.php?action=read&file="+file, function(data){ // Post with the current file
     $("#taFile").val(data); // Put file into textarea
    });
   }
  }
 });

 $("#btnSubmit").click(function() {
  var newcfg = $("#taFile").val();
  alert(newcfg); // This shows that newcfg preserves the exact value of the textarea
  console.log(newcfg); // As does this.
  $.post("/php/getFile.php?action=write&file="+file+"&newcfg="+newcfg); // This shows new lines (\n ?) as " " (a space) and removes all special characters (! , # ; : etc)
 });
});

PHP:

 $file = $_REQUEST['file'];
 $newcfg = $_REQUEST['newcfg'];
 $action = $_REQUEST['action'];
 $user = 'public';
 $config = "/home/$user/mc/$file.txt";

 if ($action == "read"){
  $oldcfg = file_get_contents($config);
  echo $oldcfg;
 } else if ($action == "write") { #if writing
  $fh = fopen($config, 'w') or die("Cant write to file"); #open file
  fwrite($fh, $newcfg); #write file
  fclose($fh); #close file
 }

I had to remove the php tags as they caused the actual PHP code to not show up. Not that some of the script is for reading the file in first, when changing tabs. That all works fine.

Thank you!

Answer №1

Important Note: Ensure that you are utilizing jQuery.post() and setting your data as $_GET parameters. The correct way to call this function is shown below:

$.post("/php/getFile.php", { action: "write", file: file, newcfg: newcfg },
   function(data){
     alert("Data Loaded: " + data);
   });

If you want to maintain your line breaks, use the following function:

function splitter($content) {
$content = str_replace(chr(10),'<br/>',$content);
$content = str_replace("<br/><br/><br/><br/>","<br/><br/>",$content);
return $content;
}

To implement the function, simply run:

$newcfg = splitter($newcfg);

Remember, paying attention to special characters is crucial according to typoknig.

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

Tips for sending PHP variables together with a Typeahead variable

I have simplified this code as much as possible. I have a typeahead variable that is functioning correctly. However, I also need to pass two unrelated variables $php_var1 and $php_var2 along with the typeahead variable. These PHP variables are initialized ...

Issue with using Sinon FakeServer with Mocha

I'm currently in the process of setting up a test for an API call. In my attempt to create a fake server within the before method, I have encountered issues with testing the basic implementation using $.ajax compared to my actual api call. Strangely, ...

What is the process for switching directories and renaming a file when uploading in nodeJs?

I am currently using multer and fs to handle the upload of an image file. How can I modify the directory where uploaded files are stored? Currently, all files are saved in my "routes" folder instead of the "uploads" folder created by multer. Additionally, ...

Positioning of the dropdown in Material UI AutoComplete menus

Is there a way to turn off autocomplete auto position? I would like the autocomplete options to always appear at the bottom. Check out this link for more information! ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Issue encountered when attempting to convert JSON string into a collection

My JSON string looks like this: "{\"Key\":3296,\"Value1\":\"Test1\",\"Value2\":\"City\",\"Value3\":\"TX\",\"Value4\":null,\"Value5\":null,\"Value6\":null}{ ...

Encountering an Unexpected Error in Next.js When Revalidating Paths

I'm facing an issue with my Next app where, despite editing a resource through an API endpoint following the pages-based system, the changes aren't reflected when I try to view or re-edit the resource. After checking the documentation, I discover ...

Could someone provide an explanation for this Jquery?

$(document).ready(function () { if ((screen.width >= 1024) && (screen.height >= 768)) { alert('Screen size: 1024x768 or larger'); $("link[rel=stylesheet]:not(:first)").attr({ href: "style2.css" ...

Trouble displaying REACT.jsx in browser

I'm currently learning React and struggling to get it running smoothly. HTML function Person(){ return ( <div class="person"> <h1>Max</h1> <p>Your Age: 28</p> </div> ); } ...

Accessing properties in JavaScript using square brackets

When I input the following code into my Chrome console: var object = {0:0, 1:1} I am able to retrieve the values by calling object[0] and object[1]. Surprisingly, even when I use object["0"] and object["1"], I still get the same results. Then, if I redef ...

Loop through a collection of arrays that contain the same elements, and multiply each consecutive element by a specified value x

I've been diving into a challenging problem involving remarkable numbers, which are defined as A number that is equal to the sum of all its proper divisors -- provided one of them is negative. For instance, the proper divisors of 12 are 1, 2, 3, 4, 6 ...

Testing the updated version 18 of Create React APP index.js using Jest

Previously, I had this index.js file created for React version <= 17. import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import reportWebVitals from './reportWebVitals'; im ...

Unable to detect click event in Vue devtools

My component is supposed to detect if a menu item has a submenu and toggle its visibility accordingly. However, when I click on it, nothing happens and no event is registered in the Vue devtools. Despite following the Vue docs closely and using the same sy ...

Secure Routes and Views with Laravel Package?

I've been creating a custom package specifically for Laravel 5.2 and I have reached the stage where I am integrating Authentication. I attempted to include an Auth folder in my resources/views directory, along with the necessary Controllers in my pac ...

Cut off a string from the start

I'm using the text-overflow: ellipsis property in a div to shorten lengthy text values. Since there is no white space in the URL, I want to prevent the overflow from increasing the width of the div. What I want to achieve is to display the following: ...

In PHP, determining whether two arrays hold the same values but in a different order

Is there a way to quickly verify in PHP if two arrays contain the same items, even if their order is different? If you are working with integer arrays, you can refer to this solution: How to check if two indexed arrays have same values even if the order i ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

Sort information based on the alphabetical order of words using AngularJS

I'm working with AngularJS and I'm looking to filter data alphabetically in AngularJS. Any assistance would be greatly appreciated! This is the code snippet I've been using: <script src="~/Scripts/angular.min.js"></script> < ...

Encountered an uncaughtException in Node.js and mongoDB: User model cannot be overwritten once compiled

Currently, I am utilizing this import statement const User = require("./Usermodel")' However, I would like to modify it to const User = require("./UserModel") Despite my efforts to align the spelling of the import with my other i ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...