0

What is the best way to pass HTML data to server. I have a htmlPage which has a div.I want to pass the innerHTML of this div to the server so that I can save it in session and recreate that div later during the edit flow. I have created a hidden field:

<input type="hidden" name="selectedTemplateHtml" id="selectedTemplateHtml" />

In this hidden field I want to set the HTML of that div and post to server. Please suggest. I tried simple passing the html from div using $("#divName").html() but when in edit flow we retrieve the stored value it gives exception since it is not able to store the html in the javascript variable as the HTML spans many lines. Please suggest.

In my case I am able to post the request with newlines and I am able to get back the html which I had posted but when I try to store it back in a javascript variable due to new line characters and double quotes it gives error

@Alexander Following code is used to display html in edit flow:

cdHtml="${postAdBean.cdHtml}";
templateId="${postAdBean.templateId}";
$("#"+templateId).html(cdHtml);

It gives exception in browser console on the first line ie.:

cdHtml="${postAdBean.cdHtml}";

This is because it is not able to convert the html returned from server to a javascript string.

Jeets
  • 3,189
  • 8
  • 34
  • 50
  • Possible duplicate of [Post newline/carriage return as hidden field value](http://stackoverflow.com/questions/667915/post-newline-carriage-return-as-hidden-field-value) – tafa Dec 09 '16 at 06:24
  • How do you retrieve the stored value in the edit flow? Who throws that exception? Can you post that code? – Alexandru Severin Dec 09 '16 at 07:42
  • can i ask what 'html' you're posting to a server, and then displaying again later? this sound SCARY if it's from any kind of user input, in that inclusion of malicious html could easily be posted and then displayed later – haxxxton Dec 09 '16 at 07:43
  • 1
    @haxxxton Scary even if its not user input, since you can always burp it and change to whatever you want. Anything and everything coming from a browser should be considered untrustworthy and malicious. – Noino Dec 09 '16 at 08:23

1 Answers1

0

Okay I got it to work thus: From client before setting the html in hidden field I encode it :

selectedTemplateHtml=encodeURIComponent(selectedTemplateHtml);
$("#selectedTemplateHtml").val(selectedTemplateHtml);

This is neccessary to escape certain characters like & in the HTML which may otherwise cause issues.

In java: String

cdHtml=URLDecoder.decode((request.getParameter("selectedTemplateHtml")),"UTF-8");
cdHtml=cdHtml.replace("\n"," ").replace("\r", " ").replace("\t", " ");
cdHtml=cdHtml.replace("\"", "\\\"");

ie. first i decode the html then replace all the newline characters and escape the double codes. Then i send the html back to browser and it is readily assignable as in javascript without any issues.

Jeets
  • 3,189
  • 8
  • 34
  • 50