HTML string gets extra newline character if sent from server to client - javascript

I'm having trouble with string manipulation. I have some code written in java, that will use an xls translator to generate some html for me - in string form.
I use spring framework to communicate this string back to my web code, but when the string arrives in the javascript, it fails with an "invalid or unexpected token error. Furthermore, when the string is written to the console, it seems that the string now containts newline characters for each new tag.
For my javascript I really need the html to be all one line.
here are some code bits:
try {
SimpleResultSet rs = dbClient.executeQuery("select MediaContent from call where id = " + callID);
if (rs.next()) {
media = rs.getString("MediaContent");
mimeType = rs.getString("MediaTypeID");
if(media.startsWith("<?xml")) {
trace.info("XSLT: " + xltString);
trace.info("Database XML: " + media);
media = Transform(media, xltString, response);
//trace.info("result HTML: " + media);
if (!media.isEmpty()) {
media = media.replaceAll("\n\r", "")
.replaceAll("\n", "")
.replaceAll(System.lineSeparator(), "");
}
}
//media = media.replaceAll("\"","\\\\\"");
}
} catch (DBException e) {
trace.warning("Failed to get call content media for call id = " + callID, e);
return media;
}
trace.info("cleaned HTML: " + media);
return media == null ? "" : media;
}
At this point the trace printing out the cleaned HTML, shows the string all on one line, without any newline characters. The string is then propagated to the ModelAndView like this:
return new ModelAndView("media", "media", mediaStr);
and on the javascript side:
<script>
var contentString = "${media}";
document.getElementById("mediaContentIFrame").srcdoc = contentString;
it is the contentString variable on the javascript side that fails with the invalid or unexpected token error.
The contentString is used to initialise the srcdoc property of an IFrame.

You have already added two checks \r\n and \n.. Also add \r and i hope it will start working :)

Related

Replace function in javascript is not replacing correct index of regex match

I have a String and I am detecting some 'urls' and 'closing anchor tags' using regex expression. firstly I am using match function which is returning the list of 'urls' and 'closing anchor tags'. further if my first url is matching with the second url then I dont need to do anything and if it is not matching then I need to replace the closing anchor tag with the same urls. here is the string:-
"This message was sent to ${EmailAddress} because you asked us to keep you up to date with the latest news and offers from the company. If you do not wish to receive these emails, please unsubscribe ${optout()}. You can also change your email preferences on our website logging in at 'a tag' class="footer-link" href="https://sample-website">https://sample-website 'closing a tag'. Please do not reply to this email, as we are unable to respond from this email address. If you need support, please visit the Sample Help Center 'closing a tag'.
var regex3 = new RegExp(/<\/a.?>/gm);
var regex4 = new RegExp(/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|[-A-Z0-9+&##\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|[A-Z0-9+&##\/%=~_|$])/igm);
var closingATag = footerContentPlainText.match(regex3);
var URLList = footerContentPlainText.match(regex4);
if(URLList != null){
for(var j =0,k=0; j<URLList.length; j++,k++){
if(j+1 != URLList.length) {
if(URLList[j] != URLList[j+1]){
footerContentPlainText =
footerContentPlainText.replace(closingATag[j],"<" + URLList[j] + ">");
}
else if(URLList[j] == URLList[j+1]){
j++;
}
}
else{
if(URLaTags != null){
footerContentPlainText = footerContentPlainText.replace(closingATag[k],"<" + URLList[j] + ">");
}
}
}
}
Although I am handing different scenarios for different type of strings but this is the scenario where I am stuck.
I expect the output, where last 'closing a tag' should be replaced by 3rd url i.e "https://support.samplewebsite.com/samplename".
Here I am not able to write a tag in actual format so I have used just text in place of the same
please help

Send an array of objects from JS/TS (Angular 2) to WCF?

i have to send an array of objects like this
[{"Cod":"1"},{"Cod":"5"}]
to my C# WCF Service which i used until today without problems with wsHttpBinding (so no JSON using here, only XML).
The request, POST, contains this param:
let param = "<cod>" + data + "</cod>";
My problem is on WCF because i can't find a way to get that array of objects from the parameter of the method:
public string GetArrayOfObjects(CompositeType[] cod)
{//implementation not important because i can't enter here...}
where CompositeType is:
[DataContract]
public class CompositeType
{
string cod;
[DataMember]
public string Cod
{
get { return cod; }
set { cod = value; }
}
}
I have tried so many things like changing the parameter to:
Object[] cod
List<string> cod
...
Everytime i get this error (translating):
Exception generated by the formatter in an attempt to deserialize the message: Error trying to deserialize the parameter http://tempuri.org/:cod. InnerException: 'Error at line 1 position 341. Expected status 'Element' .. Found 'Text' with '' name space ''. '.
...
This is the post message that i'm sending:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<s:Envelope xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<s:Header>" +
"<a:Action s:mustUnderstand=\"1\">http://tempuri.org/IService1/" + GetArrayOfObjects + "</a:Action>" +
"</s:Header>" +
"<s:Body>" +
"<" + GetArrayOfObjects + " xmlns=\"http://tempuri.org/\">" +
param +
"</" + GetArrayOfObjects + ">" +
"</s:Body>" +
"</s:Envelope>";
where param is defined before. The JSON.stringify of data inside param gives the first example of this question ([{"Cod":"1"},{"Cod":"5"}]). This post message was always fine with single value params.
Some sites show a solution with a json deserializer on wcf, but i'm using XML...it's not an option right now to re-implement the project in json.
I tried for one day but i didn't find a solution, i'd love to hear some solutions from you! Thanks to all.

c# HtmlAgilityPack and Yahoo's HTML

So I am goofing off and wrote something that first queries other websites and loads all of the pertinent stock exchange symbols and the tries to iterate through the symbols and load Yahoo's server for the latest stock price. For some reason no matter what I try to search by using HtmlAgilityPack, I can't seem to get any pertinent info back. I don't think there's an issue with some javascript running after the page is loaded (but I could be wrong).
The following is a generalized routine that can be tinkered with to try and get the percentage change of the stock symbol back from Yahoo:
string symbol = "stock symbol"
string link = #"http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=" + symbol;
string data = String.Empty;
try
{
// keep in this scope so wedget and doc deconstruct themselves
var webget = new HtmlWeb();
var doc = webget.Load(link);
string percGrn = doc.FindInnerHtml("//span[#id='yfs_pp0_" + symbol + "']//b[#class='yfi-price-change-up']");
string percRed = doc.FindInnerHtml("//span[#id='yfs_pp0_" + symbol + "']//b[#class='yfi-price-change-down']");
// create somthing we'll nuderstand later
if ((String.IsNullOrEmpty(percGrn) && String.IsNullOrEmpty(percRed)) ||
(!String.IsNullOrEmpty(percGrn) && !String.IsNullOrEmpty(percRed)))
throw new Exception();
// adding string to empty gives string
string perc = percGrn + percRed;
bool isNegative = String.IsNullOrEmpty(percGrn);
double percDouble;
if (double.TryParse(Regex.Match(perc, #"\d+([.])?(\d+)?").Value, out percDouble))
data = (isNegative ? 0 - percDouble : percDouble).ToString();
}
catch (Exception ex) { }
finally
{
// now we need to check what we have and load into the datgridView
if (!newData_d.ContainsKey(symbol)) newData_d.Add(symbol, data);
else MessageBox.Show("ERROR: Duplicate stock Symbols for: " + symbol);
}
And here is the extended method for FindInnerHtml:
// this is for the html agility class
public static string FindInnerHtml( this HtmlAgilityPack.HtmlDocument _doc, string _options)
{
var node = _doc.DocumentNode.SelectSingleNode(_options);
return (node != null ? node.InnerText.ToString() : String.Empty);
}
Any help with getting something back would be appreciated, thanks!
///////////////////////////////////////
EDIT:
///////////////////////////////////////
I highlighted the span id and then check out line 239 for where I saw 'yfi-price-change-up' reference:
The following XPath successfully find the target <span> which contains percentage of increase (or decrease) :
var doc = new HtmlWeb().Load("http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=msft");
var xpath = "//span[contains(#class,'time_rtq_content')]/span[2]";
var span = doc.DocumentNode.SelectSingleNode(xpath);
Console.WriteLine(span.InnerText);
output :
(0.60%)

json converting characters to random charaters

Hi i have email address in my database e.g "abc#yahoo.co.in" and when I retrieve it i am getting the same on my controller as well before returning that object to client but when i alert that value on my java script page, "#" is converting to some random characters and not giving proper display. How can i solve this.?
server code :
enter code here
public AppUser findById(#FormParam("employeeId") String eId ){
int id=Integer.parseInt(eId);
AppUser appUser=null;
appUser= evaluatorService.findById(id);
return appUser;
}
while debugging appUser it is giving me proper data.
my client side code :
$.ajax({
type : 'GET',
url : 'rest/evaluator/fetchEvaluatorById',
data : {
'employeeId' : employeeId
},
success : function(data) {
$('#evaluatorDetailEdit').dialog({
width: 400,
height: 400,
});
alert(data.email);
$('#employeeId').val(data.employeeId);
$('#name').val(data.name);
$('#lastName').val(data.lastName);
$('#email').val(data.email);
}
});
There is some hacky jquery-workaround - maybe there are better solutions, but this should work:
var original = "#";
alert("Original: " + original);
// Hacky jquery-workaround:
// 1. pasting encoded text as html in a "virtual" textarea and
// 2. get the decoded text:
var decoded = $('<textarea/>').html(original).text();
alert("Decoded: " + decoded);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
According to your comment, every # are change to #.
In fact, # is the HTML entity to represent the character #.
You should convert (HTML entity decode) the character on your server.
For example, in PHP, just call this function on your email strings: http://php.net/manual/en/function.html-entity-decode.php

JavaScript parse XML

I try to parse an XML string and have some problems. Here is my current state.
I have a Cordova app which reads QR-Codes (with the BarcodeScanner plugin). The QR-Code holds the XML information. When I read the code, I want to print out the XML code. Here is what I tried (the important part):
var app = {
output: null,
xmlDoc: null,
// this function is called when I click a button
scanCode: function(){
//first parameter is a callback, which is called when a barcode is detected
cordova.plugins.barcodeScanner.scan(
function (result) {
alert(result.text);
var parser = new DOMParser();
**app.xmlDoc = parser.parseFromString(result.text,"text/xml");**
app.output = document.getElementById("codeInfo");
app.traverse(app.xmlDoc.documentElement, "");
},
function (error) {
alert("Scanning failed: " + error);
}
);
},
traverse: function(node, offset){
if(node.nodeType == 3){
app.output.innerHTML += "<b>" + offset + node.nodeValue + "</b><br>";
}else{
app.output.innerHTML += offset + node.nodeName + "<br>";
var childs = node.childNodes;
for(var i=0; i<childs.length; i++){
app.traverse(childs[i], offset + " ");
}
}
}
};
My XML code looks something like this
<node><child1>text1</child1><child2>text2</child2></node>
So I expect an output like:
node
child1
text1
child2
text2
But I always get something like:
html
body
parsererror
h3
This page contains the following errors:
...
When I use a static text like
var xml = "<node><child1>text1</child1><child2>text2</child2></node>"
and use this instead of 'result.text' in the marked line, everything works as expected.
So maybe the 'result.text' is just a reference and not the value? Could this be the problem? I'm not an expert so how can I solve this problem?
P.S.: The XML code I get from the QR-Code is correct and well formed.
app.xmlDoc = parser.parseFromString(result.txt,"text/xml");
should actually be:
app.xmlDoc = parser.parseFromString(result.text,"text/xml");
There is an "e" missing in result.text
After reading Valencia's comment and the "wrong" output again and think about it, I figured out what's wrong. So the "wrong" output is just an error message in HTML format, where i print every tag. The message itself says:
This page contains the following errors:
error on line 1 at column 14: String not started expectin ' or "
The beginning should look like this
<?xml version="1.0" encoding="UTF-8"?>
but when creating the QR-Code backslashes are added
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
The first backslash is at column 14.
When I create a static XML string I insert backslashes to mask the ' " ', so my declaration and the XML code from the QR-Code look equal. But they aren't, cause the static XML string does not contain the backslashes. And these backslashes cause the error while parsing.
The easiest solution is to just not put the XML information in the QR-Code. So directly starting with the first node.
Thanks for your help.

Categories