Can not get json response using $.getJSON - javascript

I am currently developing a Ruby on rails 3 application.
My server controller function render a json object as response:
class DaysController < BaseController
...
def the_days
...
render :json => days
end
end
In my javascript,I use the following code to get json response from server( that's from the_day function in controller)
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
var result = data.response;
alert(result)
alert(data)
},
"json"
);
I use firefox browswer and checked with Firebug, in Firebug Net->XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful.
But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??
-----------------Edited------------------
I edited my code to this one:
$.ajax({
url: myURL,
type: 'GET',
data: {
emp_id: emp_id
},
dataType: "json",
success: function(data) {
alert("hi");
alert(data)
}
});
When I run this code, the browser is stuck at success: function(data)

If data is coming back null, but the response was otherwise successful, I'd say that you're sending the request in a manner that violates the Same Origin Policy.
The request needs to be sent to the same host/port/protocol that served the original page.
If this is only an issue in your development environment, you can test in Chrome by launching it from a Terminal application with --disable-web-security.
EDIT: Try changing the parameter name from data to something else, like dat or whatever.
Then try an alert:
alert( dat );
I've heard of some browsers having trouble with the data parameter when you utilize the data property of an AJAX call.

I'm guessing that the problem is that data does not have a response property. Try alerting just the data variable. It should be the days object itself.

I wish I could just leave a comment but I guess I don't have access to that yet.
Anyway, I'd start with something even more basic. Add some text alerts just to make sure you're actually making it to where you think you are. ie...
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
alert('hi') // add this
var result = data.response;
alert('bye') // add maybe even this
alert(result)
alert(data)
},
"json"
);
Sometimes when I'm debugging I find that even my most basic assumptions are wrong.
Edit: here's some sample code from working code I recently implemented
$.ajax({
url: 'users/check_username',
type: 'GET',
data: {
username: username
},
dataType: "json",
success: function(user_exists) {
alert(user_exists) // CHANGE THIS PART
}
});

It sounds like you are not sending the correct header in your ruby application. Firebug should report the response Content Type as application/json because that is what jquery is expecting it to be.
You could try changing the datatype in your ajax call to html to see if your alerts work with that, but that doesn't really help with the json parsing.

ALL, finally, I figured out the root cause. The reason is simply because of "Invalid json data" returned in server. That's in rails controller function 'def the_days':
render :json => days
should be modified to
render :json => days.to_json
Then, everything works smoothly:) Thank you all anyhow!

Related

rails passes json to javascript file, But javascript shows error

So i've got a rails call, It works lovely and passes this into postman (shortened because its huge)
SEEvent({"event_id":"ID","date":"Sat 20 Aug 2016, 10:00","suppress_best_available":"","sorted_ticket_types":["000000000001"],"is_resale_eligible":0,"ada_tickets_enabled":0,"suppress_any_price":"","expand_resale_module_ntf":1,"expand_resale_module":"","bba_deep_links_offer_code":
For some reason when i try and call it in my javascript file (which looks like this):
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '/event/'+ event,
success: function(json) {
debugger;
The error function is shown instead of the success. In the debugger, i have response code 4 and in the response text is all the json i need.
Any help would be amazing
I've tried changing the dataType to jsonp which also didnt work.
Sam
The error is happening possibly because this bit - SEEvent( is not valid json. The server needs to send valid json only which can be parsed straight away.

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Strange $.post() AJAX error when parsing JSON

I am facing this strange error in using $.post.
works
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data);
$('#loader').hide();
});
});
The above piece of code, shows me the json array I am receiving using a php file, and also shows the title field here, and hides the loader image.
But when I alert(data.title), it shows me undefined. More over, when I add datatype 'json' to $.post,
doesn't work
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data);
$('#loader').hide();
}, "json"); //Added datatype here.
});
This neither alerts anything nor does it hide the loader image. I also tried,
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
jQuery.parseJSON(data);
alert(data.title);
$('#loader').hide();
});
});
The above one too neither alerts anything nor does it hide the loader. And then I tried this one too that did nothing.
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
jQuery.parseJSON(data); //tried without this too.
alert(data['title']);
$('#loader').hide();
});
});
The strangest thing is that I have previously used json as I have shown in the 2nd script(out of 4), and that works normally. My JS console too doesn't show any errors or warning. What am I doing wrong here? How do I access the title field of data?
If this helps, here is how I send the json array,
$json = array("title" => $title, "embed" => $embed, "desc" => $desc, "duration" => $duration, "date" => $date);
print_r(json_encode($json));
I would really appreciate if someone can point out the error and tell me why my scripts are failing, similar functions worked in other js file.
here is my data, that is returned by server,
{"title":"Sunn Raha Hai Na Tu Aashiqui 2 Full Song With Lyrics |
Aditya Roy Kapur, Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"Presenting
full song \"Sun Raha Hai Na Tu\" with lyrics from movie \"Aashiqui 2\"
produced by T-Series Films & Vishesh Films, starring Aditya Roy Kapur,
Shraddha Kapoor in voice of Ankit Tiwari. \n\nSong: SUNN RAHA
HAI\nSinger: ANKIT TIWARI\nMusic Director: ANKIT TIWARI\nAssistant Mix
Engineer - MICHAEL EDWIN PILLAI\nMixed and Mastered by ERIC PILLAI
(FUTURE SOUND OF BOMBAY)\nLyrics:SANDEEP NATH\nMovie: AASHIQUI
2\nProducer: BHUSHAN KUMAR KRISHAN KUAMR Producer: MUKESH BHATT
\nDirector: MOHIT SURI\nMusic Label: T-SERIES\n\nBuy from iTunes -
https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy
& stay connected with us!! \n\nSUBSCRIBE T-Series channel for
unlimited entertainment\nhttp://www.youtube.com/tseries\n\nCircle
us on G+ \nhttp://www.google.com/+tseriesmusic\n\nLike us on
Facebook\nhttp://www.facebook.com/tseriesmusic\n\nFollow
us\nhttp://www.twitter.com/_Tseries","duration":"391","date":"2013-04-03"}
Edit
This worked suddenly.. :o
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data.desc);
console.log(data.desc);
$("#loader").hide();
}, "json");
});
In comments, you mention that this AJAX corresponds to a YouTube API.
YouTube's blog announced in 2012 that they would support CORS, which uses server-side header flags that compatible browsers interpret as permitting requests that would otherwise be prohibited by browser security Same-Origin-Policy.
Assuming, as you say, the first example worked, the first issue was "Why did (a subsequent) alert(data.title) fail? (my edit) ". If you type alert(data.title) in the console, it will fail because the scope of data is the callback function where it is defined as a parameter, and in the global scope data is undefined. If you try to pass data back to the global scope somehow, it can still be undefined because $.post returns immediately, before the data has been fetched, and merely queues a request and sets the callback function you supply to handle the reply.
The second example, which explicitly sets the $.post dataType parameter to 'json', may fail with CORS based API because the mime types for json are not allowed to be sent up to the server as Content-Type: for a simple CORS request, and $.post will as far as I know only do simple requests without preflight. $.ajax can possibly do the more complex requests if correctly applied.
The work around to keep using $.post is not to use json as the expected data type, send requests up as form data, the server may send you back json anyway if that is what the API says will happen, which can be verified while testing the code.
From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Simple requests
A simple cross-site request is one that:
Only uses GET, HEAD or POST.
If POST is used to send data to the
server, the Content-Type of the data sent to the server with the HTTP
POST request is one of application/x-www-form-urlencoded,
multipart/form-data, or text/plain.
Notice that application/json did not make the list of what Content-Type is permissible in a simple CORS request.
See also A CORS POST request works from plain javascript, but why not with jQuery?
Use ajax as
$.ajax({
url:url,
type:'post',
dataType:'json',
success:callback
})
With this type you can set lots of parameter in low level.
With datatype attribute jQuery parses JSON and send data as callback function.
I think you have to replace all single \ with double '\' to feed it to JSON.parse.

POSTing JSON data to Server URL

I am facing problem when I am posting a JSON data to the server using Ajax call in jQuery the function does not enter success mode. When I post using the POSTER Plugin of Firefox it gets posted successfully. Sharing the code snippet and screenshot of the same:
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = '{"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}}';
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/xml',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
I am getting alert number 1 and 2 but not 3.
Also when I post using POSTER plugin of Firefox, it gets posted easily.
The Response is success.
I am unable to post the same data using AJAX call.
Thanks,
Ankit
Unless and until the URL in your AJAX call is of the same Domain, I don't think it will get posted successfully. POSTER plugin of Firefox doesn't put any such restriction on the domain, but browser will put this restriction on the application.
Try checking in the error: function(){alert(4);}
to see if it reaches the error handler atleast
Please clearify what you want, when using POSTER Plugin of Firefox you have specified datatype as json where as when using ajax you are using xml.
If you what to post data as JSON use JSON.stringify which accepts JSON object and convert it to string.
Try with this code
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/json',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
Here I have changed the following lines
Converted myJSONData to a JSON object from string
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
Note: try with the string(the way you were doing) if this is not working for you
Changed datatyle to JSON
dataType: 'application/json',
Adding a header in beforeSend Function worked fine for me. Security reasons of CORS.

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

Categories

Resources