$.getJSON With Spring Not Executing Callback - javascript

I've looked around for a while now, seen many similar problems, but none that help. I have a getJSON call that calls my Spring controller and responds with JSON text (Verified that JSON text is indeed being returned), but the callback is never executed (Based that nothing executes within the callback function and I don't receive errors with bad JavaScript).
In my jsp file:
function getUserText(str)
{
$.getJSON("selectUser.htm", { id: str }, function(user)
{
//Doesn't matter what's here
});
}
In my controller:
#RequestMapping(value="/selectUser.htm")
public #ResponseBody String SelectUser(#RequestParam String id)
{
Users user = userMap.get(id);
if (user == null)
return null;
return createUserJSON(user);
}

I'm not sure about this, but my guess is the function you provide is the success function that gets called when ajax returns. It is possible that the request is not returning successfully.

It means the JSON is invalid. It could be the content is invalid or the content-type is not correctly set....
$.getJSON has no error callback
http://api.jquery.com/jQuery.getJSON/
to see what the problem is you need to use
$.ajax({
url: "myurl",
type: "GET",
dataType: "json",
success: function() {
//called when successful
},
error: function(e) {
//called when there is an error
},
});

Found the answer. Turns out that the JSON needs to be valid. I made a mistake so the JSON wasn't formatted correctly. I didn't know that the format mattered even before the callback function.

Related

retrieving json data in cross domain

I need to make a ajax call to retrieve data(json) from the RESTfull Web Service which is running in the different domain(KARAF using cxf) and the client from which the ajax call is being made, is on different domain(Apache Tomcat).
The Web Service is returning the data in the form of MediaType.APPLICATION_JSON but due to cross domain call I am receiving the data in the form of jsonp object.
$.ajax({
url: "http://localhost:8181/cxf/view/ID_123",
type: "GET",
crossDomain : true,
contentType: "applicaion/json",
dataType : "jsonp",
jsonpCallback : 'myJsonCallBack',
sucess : function(json) {
alert("Success Called");
},
error : function(xhr) {
alert("Error");
}
});
and the myJsonCallBack funcation is as below..
function myJsonCallBack(data) {
alert("Callback Called");
}
The web service method is as below..
#GET
#Path("/view/{userid}")
public ViewPreference getViewPreference(#PathParam("userid") String userId) {
ViewPreference viewPreference = new ViewPreference("GRID VIEW");
return viewPreference;
}
which is returning json object as below..
{
"viewPreference": {
"preference": "GRID VIEW"
}
}
The problem is when ever I make a ajax call neither the success callback runs nor the myJsonCallBack only error is run.
while checking in firebug it is showing some syntax error telling SyntaxError: missing ; before statement {"viewPreference":{"preference":"GRID VIEW"}}.
How to resolve this problem..?
here's what you should do:
you should return this from the server:
'myJsonCallBack({"viewPreference": {"preference": "GRID VIEW"}})'
rather than this: {"viewPreference": {"preference": "GRID VIEW"}}
this will call the myJsonCallback function and others without syntax errors
hope this helps :)

The error function not working

Hi I just tried testing if the error function would return an alert but it didn't fire. I altered the url link hoping that it would generate an alert since it won't be able to find or get json data. All I am getting is "Uncaught TypeError: Cannot read property 'length' of undefined jquery-1.9.1.min.js:3"
$(document).on('pagebeforeshow', '#blogposts', function () {
//$.mobile.showPageLoadingMsg();
$.ajax({
url: "http://howtodeployit.com/api/get_recent_po",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (data) {
$.each(data.posts, function (key, val) {
console.log(data.posts);
var result = $('<li/>').append([$("<h3>", {
html: val.title
}), $("<p>", {
html: val.excerpt
})]).wrapInner('');
$('#postlist').append(result).trigger('create');
return (key !== 4);
});
$("#postlist").listview();
},
error: function (data) {
alert("Data not found");
}
});
});
I think the problem is that, when you make the AJAX request your code is executing the success callback, not the error callback. Thus when you execute:
$.each(data.posts, function(key, val) {
The $.each function is trying to get the length of data which is NULL.
It doesn't look right that you have defined a jsonp callback function and yet your still using the success and error callbacks. This SO question might help a bit :
Use of success / jsonpCallback with ajax request
Maybe here $.each(data.posts, data.posts is undefined and that's why you get an error. Log data in success callback and see what it contains.
I created a clean Fiddle. Opening the given URL gives a 301 redirect followed by a 200 JSON response. The HTTP status code says that everything is fine, so jQuery doesn't know there was an error.
You mixed up two different concepts here: jQuery's error callback is for network errors and all these things. If you transport error states inside your JSON with HTTP status code 200 you have to deal with it on your own inside the success callback.
Sorry, SO doesn't allow JS-Fiddle links without code:
beforeSend: function() { console.log('beforeSend'); },
complete: function() { console.log('complete'); },
success:function (data) { console.log('success') },
error: function(data) { console.log('error') }
Thanks everyone for your input. I did take on-board all suggestions. Recommendation from Jason seems to had made more sense so while investigating his suggestion I came to this site to read up more about jasonCallback. removing the jasonCallback option though did not fix the issue but strangely this issue seems to do with the url I was using for my json caalback.
What I then did was to change the url from "http://howtodeployit.com/api/get_recent_po" to "http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories" and it worked. Even though both returned error in the console but the second was the one that triggered the error function. Why I am looking into it.

How do I read this weird server response and get the "success" key?

I am using this jQuery basic ajax reader:
$.ajax({
url: url,
dataType: 'jsonp',
success: function (data) {
console.log('data is', data);
}
});
The full server response I get is:
jQuery17107194540228229016_1350987657731({"action":"", "type":"", "callerId":""},
{"errorCode":0,"errorDescription":"OK","success":true,"payload":null});
However, when I try to output it with the console.log('data is,data); the output I get is:
data is Object {action: "", type: "", callerId: ""}
How do I receive the other part of the server response?
ie: The part that tells me success:true:
{"errorCode":0,"errorDescription":"OK","success":true,"payload":null}
Try this, I don't know if it will help:
success:function(data, second){
console.log('data is',data, 'second is ',second);
As several people has pointed out, the success function will only return if the request is a success. But if you have some special reason why you want to use those return values, you could add an extra parameter ( I think, still haven't tested it myself ).
success callback from jquery request will always be success even if the response is a 404. As long as the server was reachable, that is always a success. Only when server is not reachable or request got lost in the way the error callback is triggered. From that perspective, you'll always have to analyze the output to see if the result is the desired (that or check the status code of the response. If it's 40x, then it's probably an error from your perspective).

The code inside $.getJSON() is not executed

I can't figure out what is wrong here.
$(function() {
$('#cars').change(function() {
var cars = $('#cars').val();
$.getJSON('http://fooobar.com/data.php?id='+cars, function(data) {
alert('test');
});
});
});
Request to http://fooobar.com/data.php?id=3 returns json string like this
[{1: "sdadd"}]
The problems is that code
alert('test');
is not executed when request to data.php returns correct json string but is executed when no data is returned.
What I miss ?
[{1: "sdadd"}]
is not a correct JSON string. You can't have numbers as keys in objects and these keys can't start with a number.
That's why jQuery doesn't execute your success callback:
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
According to the documentation:
As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently
You can try this to check if I'm right:
jQuery.getJSON(...).error(function() { alert("error"); })
I'd guess it's the Same Origin Policy, which stops a webpage calling AJAX on another domain.
You are using incorrect format to do a cross domain data request.
You need to do return JSONP data, not JSON .
For JSONP to work, your URL :
http://fooobar.com/data.php?id=3
which normally returns { "result" : "some data" }
when called with any callback function name ,eg :
http://fooobar.com/data.php?id=3&callback=myJavascriptFunction
should return : myJavascriptFunction( { "result" : "some data" } )
only then it can call your callback javascript function with JSON data.
example:
see the out of these two api calls to facebook api which supports JSONP format :
i) JSON :
https://graph.facebook.com/19292868552
ii) JSONP :
https://graph.facebook.com/19292868552?callback=myFunctionName
Read more here : http://api.jquery.com/jQuery.getJSON/
Same origin policy is the problem here, as others have said.
But here's what they didn't say - how to fix it:
$.ajax({
url: "someurl.com",
dataType: "jsonp",
data: {'some key':'somevalue', 'someotherkey':'val'},
success: function(response) { alert(response); },
error: function(jqXHR, textStatus, errorThrown) {
//do some error handling
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
}
});
Here I'm using the $.ajax method - basically $.getJSON is a wrapper for this with dataType:'json'.
Note: this will change your request so that it passes in a param called "callback" which will be completely random. This needs to be processed by the server and passed back as a function name: i.e
Your request:
someurl.com/?something=something&callback=123456
Should return:
123456({ "key":"value"});
And that should allow you to get the returned data as normal.
Reference:
The bit on JSONP and the various options that can be used in $.ajax is quite good here:
http://api.jquery.com/jQuery.ajax/
Wikipedia has an alright article on it here: http://en.wikipedia.org/wiki/JSONP#Padding
Edit: also doing the request like this and using an error function will allow you to throw any errors to the console or alert boxes, so you can check if your returned JSON is valid or not too. Markup edited to throw an alert box on failure.

jQuery $.getJSON not working

I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});

Categories

Resources