The code inside $.getJSON() is not executed - javascript

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.

Related

Sending a json object using ajax to a servlet and receiving a response json object

I'm trying to send a json object using ajax to a servlet. The object is to be changed and sent back to the client. This is the code I used to send the json object from client to server.
function sendJson(jsonObj)
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
}
I only have a basic knowledge of javascript. As I understand this piece of code just sends a json object to a servlet. When receiving the response from the servlet, how do I get it? I searched for this and found functions similar to above function to receive response. I don't understand what this success: function(data) part does.
Can someone explain me the way to send a json object and receive the response to and from a servlet.
When I send a json object to the servlet, is there any way I can know whether it is received by the servlet, other than sending the object back as the response.
Ver simply, the answer is already in your code.
The ajax method of jquery has to callback methos for success and error.
Both are already impl. in your example but doing nothing!!
Here your code with comments pointing to the callback impl.
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
// PROCESS your RESPONSE here!!! It is in "data"!!!!
},
error: function(data) {
// This is called when the request failed, what happend is in the "data"!!!
alert('fail');
}
});
}
Impl. something in the success callback and debug it with your browser dev tools to see what's inside of "data".
As you changed your question more about how to handle the communication in general and how to know if your request was received. Here my normal approach.
First I define an envenlope for every request and response which is always the same. It can look like this:
{
status: OK | ERROR,
message: "possible error message etc."
data: JSON Object representing the payload.
}
After doing this I can impl. a generic logic to send and receive message between server and client and every side nows how to handle the envelope. To make sure a message is received, could be processed etc.
Then you have this:
Make an ajax call to your server.
2a. If there is topoligical problem your error callback on client side is called. Request failed, server not reachable!
2b. The message was received by the server. The server can now process the payload regarding the URL used to call the server. The server method succeed it will write an OK in the envelop and his possible result in "data" as payload. If the method fails, it sets "status" to "ERROR" and provides an proper message, data is empty.
The client receives data on the success callback and it can inteprete the "status" field if it's a usefull response or if it's an error.
Hope that helps
The success:function() part goes like this
A function to be called if the request succeeds. The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified
a string describing the status
the jqXHR (jQuery-XHR) object
What this means is - if your ajax request was successful, the server will return you some response, ie, the data. This "data" can be used in the function.
$.ajax({
...
success: function(data) {
// process the "data" variable
console.log("SERVER RESPONSE");
console.log(data);
}
});

jQuery nested within .get request won't execute

I have the following jQuery get request, which returns html text under the key name "data":
$(".article").click(function() {
$.get("<%= click_path %>", function(data) {
$(".article").html(data);
});
});
All the code executes except the line $(".article").html(data);. In fact, any jquery code I put inside the get request fails to execute, even though it all works fine if I move it outside the get request. Does anyone see anything wrong with my syntax?
jQuery's $.get method is an alias to $.ajax with an assumed HTTP request method of GET and without the ability to specify many options. You give it a URL and a function to run on successfully retrieving that URL. It tries to GET that URL and, if it can, the success function will run. If it can't, or if something is wrong with the response data, it fails silently and will not run the given function.
That being the case, I would assume your request is failing somewhere.
You need to look in the developer's console for errors and to inspect the request.
You can also change your code to use $.ajax and pass in the options, along with your current params, an error method. If the error method is called, you'll receive as params the jqXHR instance, a string textStatus, and a string errorThrown. Pass these into console.log and look at them for clues as to what is wrong as well.
$(".article").click(function() {
$.ajax({
url: "<%= click_path %>",
success: function(data) {
$(".article").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
});
Chances are, your ajax request fails to execute and as result, your jQuery code inside the callback never runs.
Run the following instead and see if an error is alerted:
var jqxhr = $.get( "<%= click_path %>", function() {
alert( "success" );
}
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});

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).

$.getJSON With Spring Not Executing Callback

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.

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