Accessing Oracle ATG variables with Javascript - oracle

I am trying to pass the contents of a bean to javascript so that I can parse it and create a JSON object... (Yes I am still on ATG 9.1). However I am having trouble getting from serverside to client side.... I am new with this stuff and would appreciate any explanation as documentation on this is scarce and not helpful.
<dsp:tomap var="cartMap" bean="MyShoppingCartModifier.order" recursive="true"/>
<script>
var myCartMap = "${cartMap}";
//Logic (easy)
</script>
Doing this generates an "Uncaught SyntaxError: Unexpected token ILLEGAL" on my browser (Chrome)
Any wisdom will greatly help me in my quest in learning this stuff.

The problem is your usage of the tomap tag. You can't just pass in an entire tomap'd object because the tomap tag isn't going to create a nice, parsable json object.
You should either:
1) Format the json yourself right within your tags. Choose only the values that you want from the order.
<script>
var myCart = {
total : '<dsp:valueof bean="MyShoppingCartModifier.order.priceInfo.total">'
...
}
// Then use myCart for something here
</script>
or 2) There's a little known JSP to JSON library found here, http://json-taglib.sourceforge.net, that is very useful. To use that, you'd create a separate page, something like orderJSON.jspf, that is used to generate a pure json object from your order. Then in the page that you require this js, you can do:
<script>
var myCart = <%# include file="/path/to/orderJSON.jspf" %>
// Then use myCart for something here.
</script>

Related

OpenUI5: Issue with adding a view to an element

I try to include an HTML-View in a XML-View which actually shouldn't be a problem. Unfortunately the content of the HTML-View is not added to the site. An error is not thrown.
In the XML-View I have a placeholder for the HTML-View:
<html:div
id="helptext">
</html:div>
In the controller of the XML-View I instantiate the HTML-View and add it to the placeholder:
var oController = sap.ui.controller("dividendgrowthtools.view.textviews.dividendcomparehelpDE");
var oTextView = sap.ui.view({
viewName: "dividendgrowthtools.view.textviews.dividendcomparehelpDE",
controller: oController,
type: sap.ui.core.mvc.ViewType.HTML
});
var oHelpText = this.getView().byId("helptext");
oTextView.placeAt(oHelpTextDiv.sId);
That's the content of the HTML-View:
<template data-controller-name="dividendgrowthtools.view.textviews.dividendcomparehelpDE">
<p>This is a test.</p>
</template>
Does anybody have an idea what the problem could be?
you need to be aware of the functionality of this.getView().byId();
SAPUI5 generates another ID then the one you specified in the XML-View("helptext") see:
So you need to pass the right ID. You need to be aware that these ID could possibily change, when you refactor the XML structure.
I would recommend you, not to use HTML elements in SAPUI5.
Some helpful links:
https://scn.sap.com/thread/3551589
https://plnkr.co/edit/wDBpQuxIWd0WGOoyulN0?p=preview (made by me)PLnkr Link

configuring ajaxAppender of log4javascript with Django backend

I am trying to configure ajaxAppender of log4javascript in DJango. I have made a file frontendlog.json where I want to write the logs going from the front end. This is how I write the script in myPage.html.
<script type="text/javascript" src="/static/js/log4javascript.js"></script>
<script language="javascript">
var url = '/frontEndLog/';
var log = log4javascript.getLogger("serverlog");
var ajaxAppender = new log4javascript.AjaxAppender(url);
ajaxAppender.addHeader("Content-Type", "application/json");
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
window.onerror = function(errorMsg, url, lineNumber){
log.fatal("Uncaught error "+errorMsg+" in "+url+", line "+lineNumber);
};
log.info("Front End Log");
alert('!!')
</script>
In my django urls.py I have this entry url(r'^frontEndLog/$', 'TryOn.views.frontEndLog'),
and in my django view I have this view function
def frontEndLog(request):
LOGGER.info ("frontEndLog")
return render_to_response('frontEndLog.json', mimetype="text/json")
So I expected the frontEndLog to be written in frontEndLog.json in the same location as other HTMLs are found in django. However, it tells me that XMLhttpRequest Request to URL returned status code 500. Can somebody please tell me where I am going wrong here and is this the correct way to use log4javascript in django?
I solved it. I printed the django request object in views.py. There I was able to find the log messages in the request.POST. It appears in the form of a dictionary since it is JSON-ified. You can access the logs with this
clientLogs = request.POST.get('data')
'data' is the key in the key : value pair here. (You can easily understand that when you see the POST object).
Whether you want to print it in the views.py itself or write it to a a txt file is up to you. So all this while the logs were actually getting logged without me being able to identify it! I guess I should have read the documentation better.

getting value of several textarea from WYMeditor

I would like getting the value of two textarea from WYMeditor:
The first one:
<script type="text/javascript">
jQuery(function() {
$(" .wymeditor").wymeditor({
logoHtml: '',
lang: 'fr',
skin: 'default',
});
});
</script>
And the second one:
<script type="text/javascript">
jQuery(function() {
$(" .wymeditor_ref").wymeditor({
logoHtml: '',
lang: 'fr',
skin: 'silver',
});
});
</script>
HTML:
<textarea id="definition" class="wymeditor" name="definition"/></textarea>
<textarea id="references_definitions" class="wymeditor_ref" name="definition"/></textarea>
I'm using this: WYMeditor.INSTANCES[0].html();
But, the problem is I don't know how to do if there are two textarea. How getting the second value?
Thanks a lot!!
Get specific WYMeditor instance HTML with known ordering
If you simply want to iterate through the results of all the WYMeditor instances on a particular page, your array index method is just fine. If you know the order in which the WYMeditor instances are created, you'll do something like:
var wymResults,
wymRefResults;
wymResults = WYMeditor.INSTANCES[0].xhtml();
wymRefResults = WYMeditor.INSTANCES[1].xhtml();
Get HTML from all WYMeditor instances
If you have an unknown number of instances of WYMeditor, this is how you might get the results of all of them:
var results = [],
i;
for (i = 0; i < WYMeditor.INSTANCES.length; i++) {
// Do something with the xhtml results
results.push(WYMeditorINSTANCES[i].xhtml());
}
Get specific HTML results with unknown instantiation order
If it matters which WYMeditor instance you'd like to retrieve though, which is often the case, you'll want to store references to the specific instances when you create them. eg.
var wym,
wymRef,
wymResults,
wymRefResults;
// Instantiate my WYMeditor instances
wym = $(".wymeditor").wymeditor();
wymRef = $(".wymeditor_ref").wymeditor();
// Let's grab the results. This will probably live in some kind of `submit()` handler.
wymResults = wym.xhtml();
wymRefResults = wymRef.xhtml();
Use xhtml(), not html()
Another note specific to your example, but you should be using the xhtml() call instead of the html() call to ensure consistent, cross-browser markup.
The html() call doesn't run the resulting HTML through the parser or do any browser-specific cleanup, which means that if you were to load some html in lets say IE9 that was created in Chrome, just calling html() without making any changes will mean the resulting HTML will be slightly different. Different browsers need HTML that is slightly different to provide a consistent editing experience, and WYMeditor abstracts this away for you, assuming you use xhtml() to get the results.

jQuery GET html as traversable jQuery object

This is a super simple question that I just can't seem to find a good answer too.
$.get('/myurl.html', function(response){
console.log(response); //works!
console.log( $(response).find('#element').text() ); //null :(
}, 'html');
I am just trying to traverse my the html response. So far the only thing I can think of that would works is to regex to inside the body tags, and use that as a string to create my traversable jQuery object. But that just seems stupid. Anyone care to point out the right way to do this?
Maybe its my html?
<html>
<head>
<title>Center</title>
</head>
<body>
<!-- tons-o-stuff -->
</body>
</html>
This also works fine but will not suit my needs:
$('#myelem').load('/myurl.html #element');
It fails because it doesn't like <html> and <body>.
Using the method described here: A JavaScript parser for DOM
$.get('/myurl.html', function(response){
var doc = document.createElement('html');
doc.innerHTML = response;
console.log( $("#element", doc).text() );
}, 'html');
I think the above should work.
When jQuery parses HTML it will normally strip out the html and body tags, so if the element you are searching for is at the top level of your document structure once the html and body tags have been removed then the find function may not be able to locate the element you're searching for.
See this question for further info - Using jQuery to search a string of HTML
Try this:
$("#element", $(response)).text()
This searches for the element ID in the $(response) treating $(response) as a DOM object.
Maybe I'm misunderstanding something, but
.find('#element')
matches elements with an ID of "element," like
<p id="element">
Since I don't see the "tons of stuff" HTML I don't understand what elements you're trying to find.

Ruby - Sinatra: Asynchronously calling method with form input as parameter

I am currently trying to build a little widget that will retrieve a list of artists based on a username.
The Ruby method requires a username parameter after which an API call is made that retrieves the actual array of strings.
The web page has an input field where the user can fill out his/her username. My goal is to immediately call the ruby method and display the list of artists. My problem is being able to use the actual form input as the parameter. I figured this would be relatively easy with params[:user], in the same way it's done in a Sinatra post method. Alas, turns out it isn't.
I tried both a JS approach and directly calling the method after :onkeyup.
Javascript:
userChanged = function() {
var user = document.getElementById("username");
if (user.value.length != 0){
artists = #{RFCore::get_artists(:name => params[:user]).to_json};
art_list.innerHTML = artists
};
};
:onkeyup
:onkeyup => "art_list.innerHTML = #{RFCore::get_artists(:name => params[:user])[0]}"
I have substituted params[:user] with all variations I could think of such as "#{user}" and user.
The errors returned are undefined method []' for params[:user] and undefined local variable or methoduser' for "#{user}" and user.
Perhaps there is an easy solution to this; but the feeling is starting to creep up on me my approach is wrong to begin with. I am open to any other way of achieving this.
As far as I understood, you are generating that JavaScript dynamically. So when your Ruby code produces it, it evaluates that RFCore::get_artists expression when you are generating the JavaScript code, not when the user interacts with the web page.
If that's the case, I recommend:
Use jQuery. It makes your life much easier.
When there's some user interaction (e.g., a key press), use Ajax to communicate with your server to get back a list of artists.
Here is a small Sinatra application that demonstrates this approach:
require 'sinatra'
get '/' do
<<html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function userChanged()
{
$.get('/get-artists',
{username: $('#username').val()},
function(data){
$('#artists').html(data);
});
}
</script>
User: <input id="username" type="text">
<button onclick="userChanged();">Look up</button>
<div id="artists"/>
html
end
get '/get-artists' do
"Generate here list for user #{params[:username]}"
end
Please notice that the above code is just an example. The HTML generated is all wrong, no template language is being used, etc.

Resources