I am having a problem. I have a form submit that uses jQuery JSONP to make a call BACK to my servlet. This code is embedded in another domain, hence the usage.
Here is my form submit AJAX:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js' type='text/javascript'></script>
<script language='Javascript' type='text/javascript'>
$(\"#form1\").submit(function(event) {
event.preventDefault();
var $form = $(this),
choice2 = $form.find( 'input[name=\"personChoice\"]' ).val(),
url = $form.attr( 'action' ),
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'updatePage'
});
});
function updatePage(renderHTML) {
alert(renderHTML);
}
</script>
I can confirm in my Java servlet that the request.getParameter("callback") is populated with updatePage. What I need to do is send back a response in JSONP format within the Java Servlet. How does one do that? I have something really simple like this at the moment:
Java Servlet code:
response.setContentType("text/javascript");
PrintWriter out = response.getWriter();
String renderHTML = "{ renderHTML = 'Successful'}";
out.println(renderHTML);
I also tried JSON content type response, the alert in my javascript updatePage doesn't get called.
What is the trick with Java servlet's and response back on a jsonpCallback???
A JSONP response must be wrapped inside a function call which is specified in request with callback.
Something like
callback({ renderHTML = 'Successful'});
This should usually be taken care at a filter.
The jsonpCallback property is not what you think it is. It's a string (or a function returning a string) which jquery will use as part of the request URL. You can set it to false if you don't need that functionality. See the docs
You should use the 'success' property to set the response handler.
Something like this:
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: false,
error: function(xhr, status, error) {
alert("error");
},
success: updatePage
});
Also, the best content-type to use for JSONP is application/javascript.
Hope that helps.
Related
I have java URL which includes php page header .Now on header there is button which calls javascript function which eventually calls php file (ajax call)
the url is like this
http://localhost:8080/project/welcome.htm
header is header.php
body is javas body and again
footer is php footer.
How can I call my php page.
Please suggest
thanks
You can do this using jquery. It is the easy one
Include jquery through following link
http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
and call following function in Javascript
$.ajax({
url: "header.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
in .done function, you can do anything you want to do after calling your PHP file
Here is my jQuery Ajax code
$(document).ready(function() {
$("#submitService").click(function(){
alert("Before ajax");
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk",
headers: {"accept": "application/json"},
success: function (dataItem) {
alert("Success..");
},
complete: function (dataItem) {
alert("Completed");
},
error: function (dataItem) {
alert("Error in making engine call."+dataItem);
}
});
alert("After ajax");
}); //click()
});
When my button is clicked it enters to [complete] and [error] call back methods but NOT to "success" call back method. How can I see what the error is?
I tried to curl the same statement and I get a valid response:
curl "http://api.openweathermap.org/data/2.5/weather?q=London,uk" -H "accept: application/json"
I'm using jQuery 1.7.2
<script type="text/javascript" src='<spring:url value="/resources/jquery/js/jquery-1.7.2.min.js"/>'></script>
In FireBug it shows that request with 200 OK, but no response body. But I see response body when I do it via curl.
What could be the issue?
Thanks
I guess, it is URL encode problem. Replace comma , with encode %2C
url: "http://api.openweathermap.org/data/2.5/weather?q=London%2Cuk"
Cancel the click event
$("#submitService").click(function(e){
e.preventDeault();
...
and let jQuery do the proper encoding of the URL
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather",
data: {q : "London,uk" },
and hopefully the service and your browser both support CORS since this is a Same Origin Policy issue.
Did you notice there are no Allow-Access-Origin in Api call?
I got this on chrome
XMLHttpRequest cannot load
http://api.openweathermap.org/data/2.5/weather?q=London,uk. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://jquery.com' is therefore not allowed access.
I think you have a cross site scripting issue.
change application/json to application/x-www-form-urlencoded
i have some.jsp file which also contains javascript/jquery. i need to do below check in javascript part of some.jsp file.based on the condition i need to display a message/ forward the request to servlet which in turn servlet forwards to other.jsp.
I wrote below code:
<script type="text/javascript">
$(document).ready(function() {
var isInIframe = (parent !== window);
if (!isInIframe) {
$.ajax({
type: "GET",
url: "./screenInitializer",
success: function() {},
error: function(ob,errStr) {
alert("Failed. Try Again.","error");
}
});
}else{
$("#accessDenied").text('Access Denied');
}
});
</script>
I can call a servlet using jquery ajax. forward request to jsp is not working.it is displaying a blank page instead of other.jsp. forwards request to other.jsp as below.
//Keeps some values using request.setAttribute() then forward the request
request.getRequestDispatcher("/WEB-INF/other.jsp").forward(request, response);
Basically i dont want any response from ajax call. it just need to call the servlet which in turn servlet forwards to the jsp and displays other.jsp.all My jsps are in WEB-INF folder. Am i doing anything wrong?
Thanks!
I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.
I want to send different parameters to JSP. Is it possible to send multiple parameter to JSP in jQuery? Because jQuery is client side and JSP is server side.
Update me!
You can make an ajax request passing parameters
For example:
$.ajax({
type: "POST",
url: "userNameCheck.jsp",
data: { username: "John"}
}).done(function( msg ) {
alert( msg );
//do other processing
});
See
jQuery.ajax
Simplest case: you want to open some page with javascript (jQuery). In this case you can send parameters in request to page:
document.location.href = "http://yourdomain.com/yourpage.jsp?paramName=" + paramValue;
If you need to send data without page reloading use ajax as Jigar say.
You can do like this:
$.ajax({
type: "POST",
url: "yoursite.com",
contentType: "application/json; charset=utf-8",
data: {param1: value1 , param2: "value2", param3: "value3"},
dataType: "json",
success: Succeess,
error: Failed
});