I'm porting working PHP application to Java/Wicket.
I have a lot of complex, well written jQuery/javaScript which I would like to reuse and not change too much.
Obviously I have to change urls in ajax calls and rewrite the server side scripts from PHP to Java.
I tought this task would be simple but somehow I can't figure out how to write server side that would respond to ajax call.
Simple example:
javascript:
function f(){
jQuery.ajax({
data: 'object_type=1&object_id=2',
url: 'ajax/get_object.php',
timeout: 2000,
type: 'POST',
dataType: 'json',
success: function(r) {
alert(r);
}
});
}
Php file ajax/get_object.php:
// ... create $json_string here
echo $json_string;
I have found AbstractDefaultAjaxBehavior which I probably should use to implement server side of such ajax call, but I'm not really sure how to use it.
I'm not really Java kind of guy so try to explain step by step what sould I do :-)
Have a look at This Ajax Wicket tutorial and search for AjaxEventBehavior.
Do note that Wicket assumes that browsers lacking javascript (Braille readers for the disabled for instance) can return full pages (full page reload in stead of AJAX). If you're doing a job for the government that's usually also a requirement.
Related
I'm working on a project and it requires me to create a JSP, get the arrays from afromentioned JSP and create an excel and a PDF from those arrays while saving those on Dropbox running on my server. I pretty much got everything working, but me being new with JSP and jQuery I really can't figure out an easy way of getting those arrays to Java. I could share my code both for the server and the JSP, but figured they weren't needed as the only part I need help with is sending 3 jQuery arrays to Java and that part is pretty much completely missing.
Thanks in advance and I hope everyone is having a good day!
In client side you need ajax request.
var jsonData=[12,11,13,16,17,18,19];
var ajaxOptions={
url:"myUrl",
type:"POST",
dataType:'json',
data: {MyJSONArray:jsonData},
success:function(data){
// codes....
},
}
$.ajax(ajaxOptions);
and server side you can fetch it using getParameterValues
String[] myJsonData = request.getParameterValues("MyJSONArray[]");
I am using Jquery Ajax calls to access REStful webservices as below. The webservice is hosted on different domain.
$.ajax({
type: "GET",
url: "some url hosted on differnt domain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(responseJson) {
alert("json"+responseJson);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
Am not sure whether it is not hitting the webservice.It is going to error block but no alert is displayed. Am i doing anything wrong here?
Thanks!
You got to change the Header at you server side http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
Since it will cause forgery. For more of cors understanding http://enable-cors.org/server.html
You can't make cross domain request just like that. It might cause cross-site forgery. Check this-
http://en.wikipedia.org/wiki/Cross-site_request_forgery
Basically, to be able to do so, the server should allow you to do that. If you access some resource on a cross domain server. The server responds back with a list of allowed users for that resource. The browser reads that list. If you are not listed in that list then the browser won't show the resource to you.
Solutions:
1- You should have control of the server side.
2-you can try 'script' tags in HTML for your purpose. They are an exception to this. You can make cross-domain requests using 'script' tags and then parse the response as json.
3-Jsonp callbacks.
I haven't actually implemented in much detail because I have control over server side whenever I need. And, CDNs are open to all. So, you might want to do some reading now to figure out more.
I have been trying to extract the information from this file for the past couple of hours and have run out of options.
http://www.nationalbanken.dk/dndk/valuta.nsf/valuta-hist.xml
Currently I have the information stored as a string in a Java servlet.
When I try to send it as a response to an AJAX request, I can't seem to extract any of the attributes through jQuery (mainly the time, currency, etc.)
I don't have a whole lot of experience with XML, actually none, so after trying various methods here on StackOverflow I have come to the conclusion that I simply can't find anything that'll work for me.
$("#btn").click(function() {
$.ajax({
url: "AjaxController?command=currency",
cache: false,
dataType: "xml",
success: processXML
});
});
This is my AJAX call to the servlet, in return it gives back the file linked above loaded into a string, which then needs to be processed and extracted by the jQuery function "processXML".
I need to test the browser window width in JSP, to determine whether or not I have to set a value in the request object. Typically I would achieve this with something like this:
if(document.body.offsetWidth < xxxx){
// ...
}
But I don't know how to do it with a JSP expression.
You might misunderstand that jsp and javascript existed on same file. Yes but JSP part compiles on server side itself comes to client.
You can't do that with JSP.
JSP compiles on serverside Where as javascript plays on browser i.e on client side.
Do it with javascript.You should do it in document load
when you do if(document.body.offsetWidth < xxxx) you are doing it at client side. Now if you want to propagate some client side value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).
Here is the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
data: { windowWidth: "100"}
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form
I have an idea to make something pretty sweet but I'm not sure if it's possible. Here is an example of a very basic ajax function that I might use to establish a connection a server...
function getFakePage(userId)
{
var ajaxObject, path, params;
ajaxObject = getAjaxObject();
params = "?userId=" + userId
path = getInternalPath() + "someServlet" + params;
ajaxObject.open("GET", path, true);
ajaxObject.send();
// On ready state change stuff here
}
So let's say I have a URL like this...
https://localhost:8443/Instride/user/1/admin
And I wanted to use javascript to redirect the user to this this URL. Normally I would just do this...
window.location = "https://localhost:8443/Instride/user/1/admin";
But my idea is to create a javascript (no js frameworks please) function that could combine the ajax code with the window.location code. Basically what I would like to accomplish is to create a connection with the server via ajax, send a servlet on that server the url I would like the user to be redirected to, and then redirect the user to that URL. So that for however long it takes the user to connect to my server from wherever they are in the world they see a loading icon instead of a blank white page.
So to clarify exactly what I am trying to accomplish; I do not want to put window.location within the success of my ajax function (because that would be encompass two round trips), and I do not want to return a huge chunk of HTML for the requested resource and add it to the page. I want to establish a connection to the server with ajax, send a servlet the URL the user wants to go to, and then somehow override the ajax function to redirect that user. Is this possible?
And I know some of you might think this is stupid but it's not when you're talking about overseas users with slow dial up connections staring at white pages. If it's possible, I'd love to hear some insight. Thank you very much!
First, let me say that the best solution is finding what is causing the slowness and fixing it.
Now as to your question, yes you could do it. You could even shoehorn it onto an existing application. But it wouldn't be pretty. And it comes with it's own set of problems. But here are the steps:
Browser calls ajax cache service requesting "somepage.html"
Browser loads loading icon
Server creates somepage.html and caches it in a temporary cache, (ehcache or other library would be good, probably with file backing for the cache depending on size)
Server responds to ajax request with ID for cached page
Browser now redirects to "somepage.html?cacheId={cacheId}" where the id is from the ajax call.
Server uses a filter to see if any cache can be served up for the page instead of the actual page, thus speeding up the request.
Having said that, it would be better to just have the new page load quickly with a loading icon while it did any of the heavy lifting through ajax.
You can't do an AJAX request and a location change in one. If you want to do only one request you have to choose one of those methods. ie. return some data and replace content on your current page, or load a completely new page.
It doesn't make any sense to want to want to do both. What you could want is stateful URLs; where your URL matches the content displayed, even if that content comes from an AJAX request. In that case an easy solution is the use the # part of the URL which you can change freely (window.location.hash). Some modern browsers support changing the whole URL without causing the page to reload. I've used # with great success myself.