Sending HTML Code Through JSON
Yes, you can use json_encode
to take your HTML string and escape it as necessary to be valid JSON (it'll also do things that are unnecessary, sadly, unless you use flags to prevent it). For instance, if your original string is:
<p class="special">content</p>
...json_encode
will produce this:
"<p class=\"special\">content<\/p>"
You'll notice it has an unnecessary backslash before the /
near the end. You can use the JSON_UNESCAPED_SLASHES
flag to prevent the unnecessary backslashes. json_encode(theString, JSON_UNESCAPED_SLASHES);
produces:
"<p class=\"special\">content</p>"
Write HTML string in JSON
You should escape the characters like double quotes in the html string by adding "\"
eg: <h2 class=\"fg-white\">
How to send a JSON object using html form data
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
Best practices for passing HTML as JSON
After a lot of researching and thinking, we've decided it's better to use Javascripts own built in functions, rather than doing something manually.
Therefore we are using JSON.stringify
combined with JSON.parse
, and told backend to simply html encode their markup, instead of escaping "
and /
manually.
Sending HTML by Json
escape your "" qoutes like \"" in the <li ... >
otherwise JSON will die because its a text delimeter
var jSonTestResultReport =
@"{ ""html"" : ""<li style=\""color:green;\"">I am text</li>"" }";
Related Topics
Http Response Code After Redirect
How to Include a PHP.Ini File in Another PHP.Ini File
PHP - Returning the Last Line in a File
While ($Row = MySQL_Fetch_Array($Result)) - How Many Loops Are Being Performed
PHP Run Once and Insert Twice in MySQL Database
Pdo Prepared Statement Fetch() Returning Double Results
Is MySQLi Extension Enabled in This PHP Configuration
Convert Datetime to String PHP
Am I Correctly Supporting Utf-8 in My PHP Apps
How to Get CSV File to Download on Ie? Works on Firefox
Run a Ffmpeg Process in the Background
Increase PHP Script Execution Time
How to Display Special Characters in PHP
PHP - Add Link to a Url in a String
Session Lost After Page Redirect in PHP
Warning: Date() Expects Parameter 2 to Be Long, String Given In