html line breaks $.parseJSON

Within my website, I am currently utilizing a TinyMCE window. The method involves PHP fetching an entry from the database, decoding it as JSON, and then having in-page JavaScript parse it. However, issues arise when there are elements like style='color:#fff' or other similar formats present, causing the JavaScript to fail in parsing the JSON. Even spaces or exclamation marks can disrupt this process. I am seeking a more robust solution to avoid such fragility. Can anyone suggest an alternative approach?

Javascript

$.ajax({
    type: "POST",
    url: "Including/php/fetcher.php",
    data: { identifier: identifier, page: page }
}).done(function( msg ) {
    var data = $.parseJSON(msg);
    var text = data["text"];
    tinyMCE.activeEditor.setContent(text);
};

fetcher.php

$conn = mysql_connect($row['ipdb'],$row['usernamedb'], $row['wwdb']) or die("err");
$db = mysql_select_db($row['usernamedb']) or die("err");

$identifier = $_POST['identifier'];
$page = $_POST['page'];

$qry = "SELECT text FROM ".$page." WHERE identifier='$identifier'";
$result = mysql_query($qry) or die("An error occurred ".mysql_error());
$obj = mysql_fetch_object($result);

$text = $obj->text;

echo '{ "text" : "' . $text . '"}';

Answer №1

If you want to ensure that your JSON data is valid and properly escaped, you can use the following code:

echo json_encode( array("text" => $text, "variable2" => $value2) );

This will prevent any issues with quotes, spaces, and other potential problems in the JSON format.

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

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

Splitting data in NodeJS sockets

Whenever I encounter the need to divide data, my standard practice involves converting it into a string format. Here's an example of how I handle data in my function: socket.on('data', function (data) { var str = data.toString().spl ...

When using Vue2, pushing a string to an array simply replaces the existing string instead of appending it

My current task involves manipulating a local data array by adding and removing strings within a method. However, I have noticed that my logic always results in the array containing only a single string passed to the updateIdArr method. Even after removin ...

Enhance the axis functionality in c3.js

My goal is to display a user's financial data for the previous week, but sometimes they may not have data for all seven days. When using c3.js, I noticed that it automatically extends the 'endpoint-value' to the end of the axis. Is there a w ...

Extracting data from XML using my custom script

I attempted to extract a specific value from an XML feed, but encountered some difficulties. In addition to the existing functionality that is working fine, I want to retrieve the value of "StartTime" as well. Here is the relevant section of the XML: < ...

Step-by-step guide for building and populating a JavaScript Dictionary

Does anyone know how to create a Dictionary with a key and a list of values pair in Python? I have been able to create dictionaries with a single value for each key, but now I need to store multiple items as values for each key. Here is what I have tried: ...

Codeigniter AJAX search feature encountering a glitch

I am currently working on creating an Ajax search feature with suggested results in a dropdown menu. However, whenever I type something in, I keep encountering the error "Error while request.." and the console shows a connection refusal to the post URL in ...

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

Is it possible to access a hidden JavaScript variable in Selenium?

Is there a way to extract the array "o" that contains data used for drawing a polygon? Simply using driver.execute("return o") or console.log doesn't seem to work. Any suggestions on how to achieve this? const zt = function(e, t, n, r) { c ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

Struggling to constrain a TextField component from material-ui and encountering an issue with the inputRef

Currently, I am attempting to restrict the length of an autocomplete textfield within my project. However, when I apply InputProps={{ maxLength: 2 }}, it throws an error stating that my inputRef.current is null. Even though I have set the ref in the inputR ...

Ending the Active Element within React's Accordion Component

I have created a basic accordion component for my product page in a Next.js/react app. It is functioning mostly as expected, but I am facing an issue. When a user clicks on a new accordion item, I want the currently active one to close automatically. Below ...

Leveraging ORM for a multilingual platform

My request for recommendations revolves around using ORM instead of MySQL with PHP. I have been a CodeIgniter user, but now I am looking to switch to FUEL (http://fuelphp.com), which offers its own ORM solution. The challenge I face is that a significant ...

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...

Extract the title of a YouTube video and convert it into a string using JSONObject

I'm struggling to figure out how to extract a JSONObject from a method and convert it into a String in order to retrieve the titles of YouTube videos. public static String getTitleQuietly(String youtubeUrl) { try { if (youtubeUrl != null) ...

Steps for organizing a particular key in a map

I need assistance sorting my map based on the "time" value, but so far, I haven't been successful in finding a solution after searching online extensively. If anyone has any insights or recommendations, please share them with me. This is how my Map ...

MySQL queries sometimes struggle with handling variables

When attempting to query my database, I encounter an issue where the query only seems to work when parameters are hard coded. If I try using variables instead, the query fails to execute... The following is an example of the query with hard coded paramete ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

Import and access a JSON file from a Git package using Composer

In my current project, I have created a GitHub repository that includes a valuable file data.json. Simultaneously, I am also working on another repository which is the PHP version of this idea. Now, I need to load and parse the list from data.json. Initia ...