Parse variables from json url using jQuery - java

How I can parse parameters like "city" from json?
I have url like this: http://api.db-ip.com/addrinfo?addr=8.8.8.8&api_key=key, this return me this:
{
"address":"8.8.8.8",
"country":"US",
"stateprov":"California",
"city":"Mountain View"
}
I want to apply city (or country) variable to <input type>, to show visitors some info about location.

If you just want to load that JSON object and access the "city" field, use jQuery's getJSON method to get a native JS object in response.
$.getJSON( "http://api.db-ip.com/addrinfo?addr=8.8.8.8&api_key=key", function(data) {
// do something with data.city;
});
However, in your case, you're trying to make a cross-domain JSON request -- not allowed. Since db-ip.com doesn't allow it, you'll have to proxy the request using PHP.
Set up "dbip.php" on your server as a proxy (cf. http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html)
Then you just load JSON from dbip.php on your own server, which queries db-ip.com for you. The browser is happy because the AJAX request it makes doesn't cross domain names.

var response={
"address":"8.8.8.8",
"country":"US",
"stateprov":"California",
"city":"Mountain View"
};
$("#city").val(response.city);

Related

Jquery AJAX Result data retrieve back to client side in velocity template

I have just created an AJAX request in velocity template and able to get request at .java file as below: (java file is extended for "JiraWebActionSupport" as webwork module).
var url = "PlanIssuesAction!IssuesPlanning.jspa";
jQuery.post(url,myJSONObject,function(result) {
alert('success');
})
.done(function() { alert("in done"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
On the server side, in doIssuesPlanning method, able to get call and insert the posted data.
public String doIssuesPlanning() {
System.out.println("Success executed result appear"); //i want this value to be //retrieval at client side but it's not working. unable to receive at ajax response.
return getRedirect("PlanIssuesAction!default.jspa");
//return "result is success" //also tried instead of getRedirect ,used direct response //return but not worked, it capture at error in ajax response at client side.
}
Now I need to return the result data to the client side back at jquery "Result" parameter.
How can I achieve this? Currently, in "Result" object shows all HTML text and nothing else.
(i have set object above through - "System.out.println and expect to be retrieved at client side but not working).
Can you please let me know , what is wrong here.
Thank you.
Webwork jspa URLs return HTML since that is their purpose. Most AJAX calls would be to a REST resource that returns JSON. I'd define a new REST resource for this. More information at https://developer.atlassian.com/display/DOCS/Developing+a+REST+Service+Plugin

Post JSON Data From Javascript To Java

I'm in need of some desperate help. I've been at this for 4 hours, and I'm getting pretty worn out. :/ Here's my situation:
I have a Javascript application that is making a POST request (using jQuery $.post) to an external site. On the external site I have Apache Camel running with Jetty to expose it to the web. The web services I wrote in Camel expect JSON data for all of the requests. For instance, one request needs an id, so I send it {"id": 10}.
Here's my issue: it doesn't work from Javascript. I have a few different tools that will send post requests for me (like the Poster extension for browsers). If I use Poster and set the body to {"id": 10}, it works just fine. I get that exact string in the service.
But, if I post from Javascript, I get something different. Posting the JSON object will give me the string "id=10" on my service side. (It's OK for this scenario, but I will need actual JSON objects eventually.) If I stringify the JSON object, I get the JSON string, only all of the characters are escaped. (Ex. "%7Bid%33...").
I swear I've tried every method possible for posting the data, but I either get the weird already parsed JSON, or the escaped string (or nothing at all). Is there some way I can have Javascript NOT parse the JSON object and just send it (like my posting tool does)? If not, is there a safe, efficient way to un-escape the JSON string that I get?
I really appreciate any help.
I feel like we need a little bit more information, but take a look at this javascript plugin. It may be your solution: https://github.com/flowersinthesand/jquery-stringifyJSON
Try using jQuery.ajax and setting processData to false (defaults to true):
$.ajax({
url: '/where/to/post',
type: 'POST',
data: {"id": 10},
processData: false
});
Usually, jQuery converts anything in data to query string format like id=10. The processData flag tells jQuery to interpret it literally as a json hashmap.
Posting the JSON object will give me the string "id=10" on my service side.
Javascript does not do your this conversion, so your server does it.
It is likely that your server reacts differently based on the content-type of your POST e.g. application/json vs text/plain or text/html, a common feature of REST based services.
The answers here gave me a few hints, but ultimately, it was a lot of tweaking before it would work correctly. I had to do 3 things:
Add processData: false.
Turn the JSON object into a JSON string. The request wouldn't fire if I left it as an object (even if I changed contentType to application/json).
Change the contentType to text/plain. This sent it as a raw string.
And that's what did the trick. I now get the JSON string I want on the server side.

redirect to a different url

I have one application where i have three jsp pages, from index.jsp , control goes to process.jsp and after execution control goes to result.jsp to display data. But i want that instead of displaying data in result.jsp, control will go to another url so that that receiver url will get the requested data. that is: my url is 100.20.3.45:8085/myproject/index.jsp then after processing data i want that result should go to a different url of my same network i.e. 100.20.3.46. How can I send the requested data to this different url?
Ex:
100.20.3.45:8085/myproject/index.jsp
goes to
100.20.3.45.8085/myproject/process.jsp
after processing control will go to 100.20.3.46.
How can I send this data to a different url? what is this mechanism called?
It's called "redirecting". It's to be achieved by HttpServletResponse#sendRedirect().
response.sendRedirect(url);
If you want to send additional data along, you'd need send it as request parameter(s) in a query string, but they will be visible in the URL in browser's address bar. If that isn't affordable, consider storing it in a shared datastore (database?) and then pass alone the unique key along.
Alternatively, you can also just let the <form> action URL point to that different host directly without the need for an intermediate JSP. As another alternative, you could also play for proxy yourself with help of for example URLConnection.
Unrelated to the concrete problem: having controller/business logic in JSPs is a bad practice. I suggest to take some time to learn about servlets.
Redirect to URL
window.location.href = "url"
Examples of use
window.location.href = "/process_payment";
var username = #json($username);
window.location.href = '/' + username;
window.location.href = '/{{ $username }}';

Getting Session data in Ajax call

hi I am querying database to load all items based on some criteria and setting this result in session as
data = service.getData();
session.setAttribute("data", data);
now I am trying to access this data via an Ajax call and my Ajax call is served by a different servlet rather then which fetched the data from DB.
Ajax call using jquery
$.ajax({
type: "POST",
url: "/com/tp/AjaxXML.jsp",
data: ({cmd: "report"}),
dataType: "xml",
success: function(xml) {
$(xml).find('site').each(function(){
var url = $(this).attr('url');
});
}
});
in my AjaxXML.jsp
I am doing
if("report".equals(cmd)){
List<Object> data = (List<Object>)request.getSession().getAttribute("data");
if(data == null){
System.out.println("data is null ");
}
}
every time I am getting the data as null via the Ajax call how ever I try to access the session data normally from my first servlet it works.
could someone let me know if I am doing something wrong?
I noticed one more thing when we do session.getId(); and pageContext.getSession().getId();
both of them are returning different Id's? Is this expected to me they should be same anyone differ on that?
I noticed one more thing when we do session.getId(); and pageContext.getSession().getId(); both of them are returning different Id's? Is this expected to me they should be same anyone differ on that?
No, they should definitely not differ. I however assume that you have examined them within the same request. If you examined them in different requests, then the difference can be explained by the absence of the proper JSESSIONID cookie. Cookies are domain and context specific. You're apparently sending the ajax request to a different domain/context. The leading slash / in the ajax URL also confirms this less or more. Make sure that you're sending it to the same domain/context. Use a context-relative URL, something like as url: "AjaxXML.jsp" and move the code to the same domain/context, or turn on session sharing between different contexts at server level.
Unrelated to the concrete problem, doing the Ajax response handling in a JSP is a bad idea. Rather do it in a servlet.
Replace
url: "/com/tp/AjaxXML.jsp",
by
url: "/com/tp/AjaxXML",
and put the code in doPost() method of the servlet which is mapped on that URL pattern.
See also:
How to use Servlets and Ajax?

PlayFramework. JSONP view. How?

I need that controller return JSONP response.
Something like this:
jsonp123({"name" : "Remy", "id" : "10", "blog" : "http://site.com"});
I know, that PlayFramework can send response as html Template, JSON, XML... but how send JSONP response?
Thanks.
You can take a look at how it's done for JSON (renderJSON() throws a RenderJson object) and implement JSONP response in a similar way. The only difference is that you need to surround Gson output with a function call and that content type should be text/javascript.
You can set the header type to "text/javascript" and then call renderText. (The render methods only set the mime type if you don't.)

Categories