JQuery AJAX doesn't get to success call back function - java

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

Related

Java Servlet Ajax 404 errors with jQuery [duplicate]

I am trying to call a servlet using ajax call as below:
$.ajax({
url: 'CheckingAjax',
type: 'GET',
data: { field1: "hello", field2 : "hello2"} ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
alert("success");
},
error: function (errorThrown) {
//your error code
alert("not success :"+errorThrown);
}
});
However, it goes to error function and shows alert:
not success :Not Found
How is this caused and how can I solve it?
When you specify a relative URL (an URL not starting with scheme or /), then it will become relative to the current request URL (the URL you see in browser's address bar).
You told that your servlet is available at:
http://localhost:8080/FullcalendarProject/CheckingAjax
Imagine that the web page where your ajax script runs is opened via:
http://localhost:8080/FullcalendarProject/pages/some.jsp
And you specify the relative URL url: "CheckingAjax", then it will be interpreted as:
http://localhost:8080/FullcalendarProject/pages/CheckingAjax
But this does not exist. It will thus return a HTTP 404 "Page Not Found" error.
In order to get it to work, you basically need to specify the URL using one of below ways:
url: "http://localhost:8080/FullcalendarProject/CheckingAjax"
This is not portable. You'd need to edit it everytime you move the webapp to another domain. You can't control this from inside the webapp.
url: "/FullcalendarProject/CheckingAjax"
This is also not really portable. You'd need to edit it everytime you change the context path. You can't control this from inside the webapp.
url: "../CheckingAjax"
This is actually also not portable, although you can fully control this from inside the webapp. You'd need to edit it everytime you move around JSP into another folder, but if you're moving around JSPs you're basically already busy coding, so this could easily be done at the same time.
Best way would be to let JSP EL dynamically print the current request context path. Assuming that the JS code is enclosed in JSP file:
url: "${pageContext.request.contextPath}/CheckingAjax"
Or when it's enclosed in its own JS file (good practice!), then create either a global JS variable:
<script>var contextPath = "${pageContext.request.contextPath}";</script>
<script src="yourajax.js"></script>
With
url: contextPath + "/CheckingAjax"
or a HTML5 data attribute on the document element:
<html data-contextPath="${pageContext.request.contextPath}">
<head>
<script src="yourajax.js"></script>
With
url: $("html").data("contextPath") + "/CheckingAjax"

How to get a file from Content-Disposition in java?

i am trying to post a file form my jsp and wnat to get on my servlet page but i ma not geting what ever code i did i mention below
index.jsp
</form>
jquery :
$.ajax({
url: '/test/picctureUpload',
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(response) {
// console.log(response);
var dataString = jQuery.parseJSON(response);
console.log(dataString.path);
}
});
i have written following code in server side:
Part part = request.getPart("files"); // input type=file name=xxx
log.debug("Get content type==>"+part.getContentType());
log.debug("Get file name==>"+part.getName());
i am getting java.lang.NullPointerException here, how can i solve this issue?
Thanks
form data post:
-----------------------------9962829018914
Content-Disposition: form-data; name="file"; filename="297994_231238580266568_1872824895_n.jpg"
Content-Type: image/jpeg
Check the java doc here: http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html
You will see a detailed example of upload servlet.

How to call PHP page through ajax call on java page

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

Rendering JSONP in HTML format on Java Servlet response

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.

send parameter to Java Server Pages (JSP) using jQuery

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
});

Categories