json converting characters to random charaters - javascript

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

Related

Problems with encoded special characters using $windows.location and ASP.NET MVC

I have a javascript code where I do a window.location to an .net mvc action. id is a number e.x. 1234, while name is a name with special character. E.x. "Røed"
$window.location = "/mycontroller/myaction/?id=" + query.id + "&name=" + query.name;
In fiddler I can see that the request url becomes:
mydomain.com/controller/action/?id=1234&name=R%C3%B8ed
When I in my ASP.NET MVC controller tries to get the query string values from Request.QueryString, I get something which looks like a double encoded string:
public ActionResult MyAction(LandingPage currentPage, string state)
{
string queryString = Request.QueryString.ToString();
var cultureName = CultureInfo.CurrentCulture.Name;
querystring becomes: "id=1234&name=R%u00f8ed"
As you can see, the encoding from the request url doesn't look the same as the one in asp.net. why?
I need to use the decoded name further in my application (Røed). How can I accomplish this?
Try this on the javascript side (to ensure you encode each part correctly):
$window.location = "/mycontroller/action/?id=" + encodeURIComponent(query.id) + "&name=" + encodeURIComponent(query.name);
and this on the MVC side:
public ActionResult Action(string id, string name)
{
}
or, using your example now that you've provided it:
public ActionResult MyAction(LandingPage currentPage, string state, string id = null, string name = null)
{
if (id != null && name != null)
{
}
}
and then name should be interpreted correctly. Because you're using the QueryString directly, it's the encoded query string.
If you really need to, you can parse the query string using HttpUtility.ParseQueryString(...) which will give you a NameValueCollection, but this isn't the correct way to do things.

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

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 :)

How To Add Url To An ng-repeat If Not Provided In JSON Object

I have a JSON object returning from a httpq call. One of the properties is LinkUrl. Sometimes this will have a predetermined url that comes from the returned object, other times it will just have a file name in which I'll need to prepend a base url to the beginning of that file name.
Not sure if there is a more angular way to do this or if it needs to be a regex if statement.
Below i have the returned LinkUrl that is just the file. If there is no url, I need to prepend a url to the file where it will be hosted so it outputs http://mycorp.com/stores/files/store11_OKC_Docs.pdf to my view.
Any help appreciated.
0: Object
$$hashKey: "00B"
GroupId: "1"
GroupName: "Store # 11 - OKC"
LanguageName: "English"
LinkTypeAbbr: "Store_Docs"
LinkTypeDescr: "Store Documents"
LinkTypeId: "1"
LinkUrl: "store11_OKC_Docs.pdf"
You can do something like
<a href="{{'http://' in obj.LinkUrl ? obj.LinkUrl : baseUrl + obj.LinkUrl}}" >{{obj.GroupName}}</a>
You can use regex for checking whether that field is url or not. You can find answer for that here >> https://stackoverflow.com/a/5717133/211458 (shared code below)
function ValidURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
if (!ValidURL(yourObject.LinkUrl)) {
yourObject.LinkUrl = yourAddress + yourObject.LinkUrl
}
file
$scope.chckeURL = function(url){
/*Check here this is only a file name or full URL.
using HTTP is present in the string or not.
generate final url and return it
*/
return finalURL;
}

Extract JavaScript String from HTML page with Java

I want to get the value of a particular Javascript variable hard-coded in a html page. Visit the test-case with the following instructions:
Go to the website : http://www.headphonezone.in/
Open console
Type : Shopify.theme
Output is : Object {name: "Retina", id: 8528293, theme_store_id: 601, role: "main"}
Type : Shopify.theme.theme_store_id
Output is : 601
The above response comes from the script given below, which is present in all the Shopify stores.
<script>
//<![CDATA[
var Shopify = Shopify || {};
Shopify.shop = "headphone-zone.myshopify.com";
Shopify.theme = {"name":"Retina","id":8528293,"theme_store_id":601,"role":"main"};
//]]>
</script>
How to write a java code to get the value of Shopify.theme.theme_store_id field and store it?
Get the html page as a String (see this post)
Detect the "Shopify.theme" keyword with a regex:
.
String patternString = "Shopify.theme\\s*=\\s*.*theme_store_id\\"\\:(\\d+)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
String themeStoreId;
while (matcher.find()) {
themeStoreId = matcher.group(1);
}

how to get full path of URL including multiple parameters in jsp

Suppose
URL: http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
<%
String str=request.getRequestURL()+"?"+request.getQueryString();
System.out.println(str);
%>
with this i get the output
http:/localhost:9090/project1/url.jsp?id1=one
but with this i am able to retrieve only 1st parameter(i.e id1=one) not other parameters
but if i use javascript i am able to retrieve all parameters
function a()
{
$('.result').html('current url is : '+window.location.href );
}
html:
<div class="result"></div>
i want to retrieve current URL value to be used in my next page but i don't want to use sessions
using any of above two method how do i retrieve all parameters in jsp?
thanks in advance
Given URL = http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
request.getQueryString();
Should indeed return id1=one&id2=two&id3=three
See HttpServletRequest.getQueryString JavaDoc
I once face the same issue, It's probably due to the some testing procedure failure.
If it happens, test in a clear environment : new browser window, etc.
Bhushan answer is not equivalent to getQueryString, as it decode parameters values !
I think this is what you are looking for..
String str=request.getRequestURL()+"?";
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements())
{
String paramName = paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++)
{
String paramValue = paramValues[i];
str=str + paramName + "=" + paramValue;
}
str=str+"&";
}
System.out.println(str.substring(0,str.length()-1)); //remove the last character from String

Categories