How Spring MVC send view result with data to ajax code? - javascript

I have a Spring MVC application and I am developing a timed quiz. I am using the Thymeleaf for the formation of the final page that the user sees. I wish I could return the processing done by Thymeleaf (vision / resulting page) to the client side, and also pass the time available for the resolution of the question to a JavaScript code.
In short, the Thymeleaf processes the vision, returning a page with the question and options to choose from, and Spring MVC returns to JavaScript code the amount of time the user has to solve the question.
The biggest problem I have is that I can give something back to JavaScript code with #ResponseBody by a message in JSON, for example. But on the server side, I just can return or a vision, or data, not both at the same time.
I could return the contents of the question, the text and the choices together as JSON response (with time of the question), but then I would be taking the work from Thymeleaf, letting JavaScript code to solve the presentation, mixing in this case, different jobs...
Is there a way to respond JavaScript code using Thymeleaf with these criteria in mind? Allowing processing presentation and return information to the client side?
OBS: If you need some sample code, put a comment and I'll be happy to edit my question (although I think there is no need for it ...).

I am afraid you can only send either one at a time. Each response from web server should be of a specific content type, for view it will be text/html for JSON it is text/json. Though, You can send separate requests for the view as well as for JSON data using ajax.

Related

Locals in Javascript/JQuery like Locals in Rails?

I create a Js Application and want to have English and German locals, which i can switch via button.
Is there a way to insert locals from a extra file in a .js file, like the function t'...' in Rails ?
As far as i know there is no way to do it directly and the reason is fairly simple too, erb is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server, However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.
a guy asks a similar question here:
http://www.quora.com/Ruby-on-Rails/Can-I-pass-a-JavaScript-variable-to-a-Rails-method
and you can learn more about AJAX here:
http://www.w3schools.com/ajax/default.asp

Using JavaScript to send String to Servlet, and Results from servlet back to JavaScript

First of all: sorry for my bad grammer. English isn't my native language, but i will try to exlpain my problem as simple as i can.
I'm working on a web-application, where user can enter a link. (Question 1) This link should be send to the server/servlet and will be progressed to other things. (Question 2) After the progression, the servlet will send a json-array (?) back to the javascript-part of my app.
I'm completly new to this kind of stuff, but its very important to me, to find out how this works or better, how i can make this work. Its actually very simple, but i used plenty of weeks and cant figure it out.
The application is using the SAP UI5-libs (Question 3), where i would also like to know, if there is any possible way, to parse JSON with the UI5 libs.
I hope, i could explain my problem good enough, so i can get some help. Thanks to all!
The 'sending' of the string to the server/servlet would happen via ajax in either POST or GET form. That is up to you.
I recommend you use a javascript plugin like jQuery (JQuery Ajax API) because the regular ajax code is a bit messy.
As for the servlet/server communicating back to the client is as simple as writing to the page. In a typical servlet context it would be something like
out.print("This is a message");
where Ajax automatically returns the content of the entire page upon callback.
So in conclusion:
Consider test.jsp your servlet. I wish to send "Hi" from the client (being the browser) via GET to the servlet and I want the servlet to say "Hello" back.
I would open an ajax request of type GET to the url "test.jsp?param=Hi". In the servlet I receive this page request and process it. The servlet discards the parameter because it is not used and outputs "Hello" to the page.
In the client the ajax will have returned "Hello" and I can use this to put it into a var or whatever and all of this happened while not refreshing and not navigating in the original document where I did the javascript.
Another way is using websockets where you basically use sockets in javascript to send and receive any kind of data.
Also please check out this possible duplicate question: How to send a string to a servlet from javascript using xmlhttprequest

request downloading a file basing on criterias from javascript

I've got a web application (php/symfony2 - but it doesn't matter here) with heavy AJAX usage and quite a lot of javascript in the client side layer. The interface enables the user to filter the data he wants to display (periods, checkboxes, selects, etc.) and basing on those choice, a POST request goes to the server side for data and JSON is returned through AJAX.
Now, I want to add a functionality to download the data file basing on the criterias/filters that reside in the javascript layer - and I'm not sure how should I do it.
Let's say I've got a <a href="some_action_url"> tag that - if I click - it downloads the file. I know how to do all the server-side stuff. But I don't know how to pass the criteria parameters from javascript to the server-side controller a using the <a> tag.

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.

Can Django/Javascript handle conditional "Ajax" responses to HTTP POST requests?

How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?
On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser.
if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)
So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.
Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.
I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.
So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?
Although you can arrange for your views to examine the request data to decide if the response should be an AJAXish or plain HTML, I don't really recommend it. Put AJAX request handlers in a separate URL structure, for instance all your regular html views have urls like /foo/bar and a corresponding api call for the same info would be /ajax/foo/bar.
Since most views will examine the request data, then do some processing, then create a python dictionary and pass that to the template engine, you can factor out the common parts to make this a little easier. the first few steps could be a generic sort of function that just returns the python dictionary, and then actual responses are composed by wrapping the handler functions in a template renderer or json encoder.
My usual workflow is to initially assume that the client has no javascript, (which is still a valid assumption; many mobile browsers have no JS) and implement the app as static GET and POST handlers. From there I start looking for the places where my app can benefit from a little client side scripting. For instance I'll usually redesign the forms to submit via AJAX type calls without reloading a page. These will not send their requests to the same URL/django view as the plain html form version would, since the response needs to be a simple success message in plain text or html fragment.
Similarly, getting data from the server is also redesigned to respond with a concise JSoN document to be processed into the page on the client. This also would be a separate URL/django view as the corresponding plain html for that resource.
When dealing with AJAX, I use this:
from django.utils import simplejson
...
status = simplejson.dumps({'status': "success"})
return HttpResponse(status, mimetype="application/json")
Then, AJAX (jQuery) can do what it wants based on the return value of 'status'.
I'm not sure exactly what you want with regards to forms. If you want an easier, and better form experience, I suggest checking out uni-form. Pinax has a good implementation of this in their voting app.
FYI, this isn't an answer...but it might help you think about it a different way
Here's the problem I'm running into...Google App Engine + jQuery Ajax = 405 Method Not Allowed.
So basically I get the thing to work using the outlined code, then I can't make the AJAX request :(.

Categories