Rails request.xhr? is not working - java

Applications - 2 (Java and Rails )
Rails - 3.0.3
Ruby - 1.8.7
Client - Ajax call using Jquery from Java App
Firebug - shows it is actually an Ajax XHR request (XHR tab )
Server - Rails - request.xhr? false
Any gem is missing for ajax response ( ajax request only from java pp )
My gem list is below:
abstract (1.0.0)
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activeresource (3.0.3)
activesupport (3.0.3)
arel (2.0.4)
builder (2.1.2)
bundler (1.3.4)
cgi_multipart_eof_fix (2.5.0)
columnize (0.3.6)
crack (0.1.8)
daemons (1.1.0)
delayed_job (2.1.2)
erubis (2.6.6)
fastthread (1.0.1)
gem_plugin (0.2.3)
hoptoad_notifier (2.3.12)
httparty (0.6.1)
i18n (0.4.2)
linecache (0.46)
mail (2.2.10)
mime-types (1.16)
mongrel (1.1.5)
mysql2 (0.2.6)
nokogiri (1.4.4)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.6)
rails (3.0.3)
railties (3.0.3)
rake (0.8.7)
rbx-require-relative (0.0.9)
ruby-debug (0.10.4)
ruby-debug-base (0.10.4)
ruby-xslt (0.9.7)
rubygems-bundler (1.1.1)
rubyzip (0.9.4)
rvm (1.11.3.6)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.23)
xml-simple (1.0.12)
My controller code is
def index
if request.xhr?
logger.debug " Ajax request yes"
else
logger.debug " Ajax request false"
end
respond_to do |format|
format.html
format.js
end
end
Jquery code is :
$.ajax({
type: "GET",
url:"someurl"
cache:false,
success: function(data) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.responseText);
}
server log is
Started GET "/mozart_content?id=phyp10084_sa102&dt=20130704132018&api=a3aee3fa-567e-11df-be64-7779fa786bb0&sign=WBCbzBY0GDAP6mQVLxcFZX-ES10%3D" for 192.168.42.27 at Thu Jul 04 18:49:44 +0530 2013
Processing by MozartContentController#index as HTML
Parameters: {"sign"=>"WBCbzBY0GDAP6mQVLxcFZX-ES10=", "api"=>"a3aee3fa-567e-11df-be64-7779fa786bb0", "dt"=>"20130704132018", "id"=>"phyp10084_sa102"}
Ajax request false
Rendered mozart_content/index.html.erb within layouts/application (149.3ms)
Completed 200 OK in 155ms (Views: 154.3ms | ActiveRecord: 0.0ms)

This is the issue...Ajax does not work on cross domain.
From Firefox Docs,
HTTP Requests made using the XMLHttpRequest object were subject to the
same-origin policy. In particular, this meant that a web application
using XMLHttpRequest could only make HTTP requests to the domain it
was loaded from, and not to other domains.

You're making a POST without specifying data. Change type to GET if you want to do a GET or add data to the request.

yes it some times give false when posted thorugh $.ajax in place of this you can check request.format == :js

Related

How to implement Spring Boot Starting/Restarting page

When I'm starting my Spring Boot application it takes time to load all needed artifacts which is totally acceptable. It takes 2 minutes for the user to wait.
Is it possible to implement starting page "Hello! We are starting... Just wait a moment" and reload it to main page when it's done? I'm using Spring Boot.
You can try this solution.
Tomcat is started when all Beans are initilizazed, so you can monitor this initilization and display on some page.
Maybe you could put HTTP server proxying your server. In case your server is down you could display a simple HTML page with the message your proposed.
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
ErrorDocument 404 /loading.html
In this page perform AJAX call to your real page. For example (for convenience I used jQuery, but you could also use vanilla javascript or another library):
function pollPage(){
$.get("http://localhost:8080/realpage", function(data) { //when page is loaded, replace content of current page
var replacePage = document.open("text/html", "replace");
replacePage.write(data);
replacePage.close();
}, function(){
setTimeout(pollPage, 10000); //If page is still inaccesible try again in 10 seconds
});
}
This would replace the whole initial page with your real page.

Making cross domain jquery ajax calls to Restful webservice?

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.

jQuery cannot access java webservice

I'm trying to write a simple 'proof of concept' front end for our webservice. The webservice is a java webapp returning simple xml running in tomcat.
The front end consists of simple html pages with some jquery functions. I'm developing the pages on my local machine while the webservice runs on one of our servers.
Basically this is what I do:
var url = "http://ourserver.com:51088/service/action/?param=123";
$.get(url,function(data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
When I put the url in the Firefox address bar, I get the resulting xml.
When I run the jquery code Firebug shows the resulting xml, but the alert never shows.
Thinking it might be a cross-browser scripting problem, I wrote a little node.js proxy server that passes any localhost:51088/path to ourserver.com:51088/path. So I changed the url var to
var url = "http://localhost:51088/service/action/?param=123";
Again, testing this url in the browser results in the xml. So the node.js proxy server is working fine.
When I run the jquery code in Firebug I now consistently get Reload the page to get source for: http://localhost:51088/.....
I'm at a loss now.
UPDATE: after reading more I changed the jquery code to:
$.ajax( {
type: "GET",
contentType: "application/xml",
url: url,
datatype: "text xml",
xhrFields: {
withCredentials: true
},
succes: function(xml) { alert(xml) },
error: function(obj, status, err) { alert ("error\nstatus: " + status + "\nerr: " + err)}
});
Now it doesn't matter if I use the remote url or the local url. Both return the xml in the console log, but the success function is still not called.
You misspelled the "success" option.
Seems to me your proxy is not working as you expect.
And as to your first problem, seems to me that it is cross-domain request issue.

SOAP web service calls from Javascript

I'm struggling to successfully make a web service call to a SOAP web service from a web page. The web service is a Java web service that uses JAX-WS.
Here is the web method that I'm trying to call:
#WebMethod
public String sayHi(#WebParam(name="name") String name)
{
System.out.println("Hello "+name+"!");
return "Hello "+name+"!";
}
I've tried doing the web service call using the JQuery library jqSOAPClient (http://plugins.jquery.com/project/jqSOAPClient).
Here is the code that I've used:
var processResponse = function(respObj)
{
alert("Response received: "+respObj);
};
SOAPClient.Proxy = url;
var body = new SOAPObject("sayHi");
body.ns = ns;
body.appendChild(new SOAPObject("name").val("Bernhard"));
var sr = new SOAPRequest(ns+"sayHi",body);
SOAPClient.SendRequest(sr,processResponse);
No response seems to be coming back. When in jqSOAPClient.js I log the xData.responseXML data member I get 'undefined'. In the web service I see the warning
24 Mar 2011 10:49:51 AM com.sun.xml.ws.transport.http.server.WSHttpHandler handleExchange
WARNING: Cannot handle HTTP method: OPTIONS
I've also tried using a javascript library, soapclient.js (http://www.codeproject.com/kb/Ajax/JavaScriptSOAPClient.aspx). The client side code that I use here is
var processResponse = function(respObj)
{
alert("Response received: "+respObj);
};
var paramaters = new SOAPClientParameters();
paramaters.add("name","Bernhard");
SOAPClient.invoke(url,"sayHi",paramaters,true,processResponse);
I've bypassed the part in soapclient.js that fetches the WSDL, since it doesn't work
(I get an: IOException: An established connection was aborted by the software in your host machine on the web service side). The WSDL is only retrieved for the appropriate name space to use, so I've just replaced the variable ns with the actual name space.
I get exactly the same warning on the web service as before (cannot handle HTTP method: OPTIONS) and in the browser's error console I get the error "document is null". When I log the value of req.responseXML in soapclient.js I see that it is null.
Could anyone advise on what might be going wrong and what I should do to get this to work?
I found out what was going on here. It is the same scenario as in this thread: jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox.
Basically I'm using Firefox and when one is doing a cross domain call (domain of the address of the web service is not the same as the domain of the web page) from Firefox using AJAX, Firefox first sends an OPTIONS HTTP-message (before it transmits the POST message), to determine from the web service if the call should be allowed or not. The web service must then respond to this OPTIONS message to tell if it allows the request to come through.
Now, the warning from JAX-WS ("Cannot handle HTTP method: OPTIONS") suggests that it won't handle any OPTIONS HTTP-messages. That's ok - the web service will eventually run on Glassfish.
The question now is how I can configure Glassfish to respond to the OPTIONS message.
In the thread referenced above Juha says that he uses the following code in Django:
def send_data(request):
if request.method == "OPTIONS":
response = HttpResponse()
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
response['Access-Control-Max-Age'] = 1000
response['Access-Control-Allow-Headers'] = '*'
return response
if request.method == "POST":
# ...
Access-Control-Allow-Origin gives a pattern which indicates which origins (recipient addresses) will be accepted (mine might be a bit more strict than simply allowing any origin) and Access-Control-Max-Age tells after how many seconds the client will have to request permission again.
How do I do this in Glassfish?
Have you actually tested that ws is working properly?
You can use SoapUI for inspecting request/response etc.
When you confirm that ws is working from SoapUI, inspect what is format of raw Soap message. Then try to inspect how it looks before sending with .js method, and compare them.
It might help you understand what is wrong.
Check if this helps
http://bugs.jquery.com/attachment/ticket/6029/jquery-disable-firefox3-cross-domain-magic.patch
it's marked as invalid
http://bugs.jquery.com/ticket/6029
but it might give you some hint
On the other hand, instead to override proper settings for cross-domain scripting might be better if you can create and call local page that will do request to ws and return result.
Or even better, you can create page that will receive url as param and do request to that url and just return result. That way it will be more generic and reusable.

Porting PHP/jQuery application to Java/Wicket

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.

Categories