How to include client side JavaScript in ssjs in xpages - javascript

I would like to include some results from client side JavaScript (csjs) into my server side JavaScript (ssjs) in XPages.
e.g. on csjs i collect the screenwidth of a device via window.screen.availWidth
I would like to use the result further in my ssjs. How can I do this?

You need to send the screen width and height from you client script to you server script.
using QueryString (location.href=...../?open&width=xxxx&height=yyyyy),
setting a field on your xpage and to a partialrefresh or using extlib remote service.
There are probably several more ways of doing it ;-)

Another approach could be, you could put your result of CSJS calculation in a hidden input field and then get those values in your SSJS code.
Also you can look into this discussion in StackOverflow for some more ideas. It basically uses partial refresh and passes the values from CSJS as parameters.
XSP.partialRefreshPost('#{id:_element_to_refresh_}', {params: p});
You could then access those parameters in your SSJS code.
And I would be repeating Fredrik, "there are probably several more ways of doing it" ;-)

Related

java session in servlet the same as sessionstorage in javascript

I have a servlet which I call the following:
request.getSession().setAttribute("name", nameObj);
Can I access it from the following page using
console.log('IH HERE' + sessionStorage.getItem('name') );
It doesn't seem to work. Either js or jquery solution would be nice.
Thanks,
Scott
This won't work, for two reasons:
sessionStorage is client-side only; it's not sent to the server via HTTP requests and the server can't write it without talking to the client.
request.getSession() is server-side only, with a session ID stored in a cookie but nothing else stored in a client-accessible format.
You'll have to use cookies if you want to achieve this effect (read / write by both) or loop over the session and provide it all in the page somewhere (read only by client).

Read browser window size using JavaScript and then pass it to C#

I would like to do the following
I need to generate n number of tabs bassed on Screen Resolution. For example, if screen resolution is 800x600, I want to generate 4 tabs using C#. If it is 1024x764, then 10 tabs.
I know I can get the height and width using screen.width and screen.height using JavaScript. I wrote it on the onload() of body and set two hidden fields to get the value in server side.
The issue is that, the server side code will execute first and JavaScript code will be executed. Am I right ? Due to this, I can not get the correct value in hidden fields when I needed. But when I use alert() in JavaScript code it shows the correct resolution.
How can I get the correct resolution in server side code?
Look for a cookie containing the screen width on the server. If the cookie doesn't exist send back a page that creates the cookie and does a redirect to the original url. When the cookie is available, use the value for the width to determine how many tabs to generate. See here for a tutorial on browser-side cookie management: http://www.quirksmode.org/js/cookies.html or use the jQuery cookie plugin if using jQuery already. You'll need to generate a new cookie value whenever the browser is resized.
Now that you have a basic outline for how to do it, let me say that I think it's better to build the tabbed interface so that it works with the same number of tabs regardless of screen width. Check out how jQuery UI tabs works by floating each tab left so that if there isn't enough screen to display them all on one line, it flows to another line (and so on).
This helped me createCookie("cookieScreenWidth", screen.width, 1); where createCookie(...) is a user defined function. I wrote the code in the login page.
So I could retrieve the vale in my page as (using C#)
Request.Cookies.Get("cookieScreenWidth").Value
Not the most elegant, but you could capture the javascript variables in one 'stub' page and then forward to an asp page, with the screen res as parameters, using Request.Params on the server side
Get the window diamensions in javascript and pass that to a server page using ajax, Get the response (HTML for 4 tab/ HTML for 10 tab) from that page now and load to the initial page
You can only get the resolution after a full round-trip (server serves a page, javascript reads the values, browser passes values to server).
This can be done through AJAX, or through posting a form, cookies or through the URL. Many different ways to achieve this.

Dynamic response with tracking pixels?

I am testing out some tracking pixel functionality in an ASP.Net 4 MVC architecture.
This article gives a nice way of setting a tracking pixel (image) that you can use to read a visitor's environment parameters and do some logging on the server side before completing the response.
What I would like to do is inject some Javascript, based on the account ID that the pixel came from. In the example above, the ID would be set by setting some query string parameters.
By the looks of that code, it can only be used to log data, as the response type is of type image.
Is it possible to accomplish this using the method shown above? If not, can I get some recommendations/sources on how to accomplish this using Javascript and tying this back into my .Net architecture where based on some logic, I can add some additional Javascript to the response?
If I have no other choice to go the JS route, I'm guessing it would be something along the lines of the Google Analytics tracking script that includes some parameters sent back through JS.
Thanks.
If the client is requesting an image and expecting an image, then that is what you need to return. Look at this type of HTML that would generate an image request:
<img src="test.jpg">
Clearing the client is expecting image bits to come back and anything besides that is going to mess up the display of that image.
If you want to put server-supplied javascript into the page, then simply have the client request some javascript like this:
<script src="test.js"></script>
Your server can then do it's logging upon that request and return whatever javascript it wants to from that request. If you want to return different javascript for every request, then you will need to defeat caching in the browser (there are a number of was to do that) so that the javascript is always requested from the server.
In general, I'm guessing that you don't need to return different javascript for every request. But rather, you can put a common block of javascript in the client page and that javascript can examine the environment and branch based upon what it finds. That's how Google Analytics works. One common piece of javascript is served to the client, that code examines the environment and then makes an ajax request with different parameters set that causes the right information to be recorded on the server.

Can Javascript get value from web.config AppSettings?

I have an aspx page, without the code behind cs file.
therefore, if I wanted to get the value from web.config AppSetting,
is it possible to do this in JavaScript or jQuery?
Appreciate if you could provide me some references, thank you.
Not directly. The config files are locked down by IIS so direct access is impossible.
You will have to go via Ajax to the server and request the setting.
Use this to make the call to the server asynchronously
http://api.jquery.com/jQuery.ajax/
You will need either a Web Method/ Service / Controller Action (if MVC) to handle the incoming request.
Alternatively send the value down in the initial page request via a hidden field or JavaScript variable set.
IIS by default will not serve Web.Config (or a selection of other file types as well) for reasonably obvious security reasons so you'd need to return your application setting to jQuery via an Ajax call or similar.
I would add a asp Hidden field and then set its value on page load from web.config.
You can access that information from JQuery.
The answer is here :
Can i read data from web.config using JQuery?
"Jquery is javascript that runs in your browser, your web.config resides on your server..."
The simple answer is : Not directly , you will have to call a webSerivce method .
It is common that you get the web.config parameters in your code behind.

How far can I go with JavaScript?

I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.

Categories