crossDomain jquery ajax not getting json - javascript

I simply created a rails 3.0 scaffold and exposed it using json, and kept it running.
So if I hit http://localhost:3001/objects.json
I see json data in browser
Next I have one plain html which includes code.jquery.com/jquery-1.7.min.js. I opened this page in firefox(ubuntu), then opened the firebug console and tried following
var myurl = 'http://localhost:3001/objects.json';
$.ajax({
url: myurl,
dataType: 'jsonp',
error: function(data){ console.log("error:"+data); console.log("error:"+data.readyState); },
success: function(data){ console.log("success:"+data); }
});
I wanted to fetch same json here in success handler, what I have observed so far is
if specified dataType: 'jsonp'
I do get json response(checked with firebug:Net), same as I see in browser
I do not get success called
I do get error called, with status code = 4, and status = "success"
else I get
response blank
And one more thing, every time I get 200 back.
Any hints ...whats going on here?
Adding my server side code and log
code =>
# GET /objects
# GET /objects.json
def index
#objects = Object.all
respond_to do |format|
format.html # index.html.erb
format.json {
render :json => #objects.to_json, :layout => nil
}
end
end
log sample =>
Started GET "/objects.json?callback=jQuery17024293556233345082_1321347517236&_=1321347853199" for 127.0.0.1 at 2011-11-15 14:34:13 +0530
Processing by objectsController#index as JSON
Parameters: {"callback"=>"jQuery17024293556233345082_1321347517236", "_"=>"1321347853199"}
[1m[35mobject Load (0.1ms)[0m SELECT `objects`.* FROM `objects`
Completed 200 OK in 11ms (Views: 5.4ms | ActiveRecord: 0.1ms)

I think you using $.getJSON may be better

Maybe you returning result in the wrong Content-type (not jsonp). If you want jQuery to fire 'success' event regardless the Content-type, remove dataType parameter from ajax options

First, I am guessing it should be Object.all
I am assuming that the server your requesting from is different from the server that provides you with JSON data. i.e. different ports in this case or I see no need to use JSONP.
JSONP is not ajax but uses the src attributes in the script tags. If your trying to access information from the same server it dataType: json should be the approach.
If you are fetching information from a different server i suggest you add to the end of your url stream a ?callback=?.
With Jquery $.getJSON should be the way to go. For example
$.getJSON(url, data, function(response){
// Do something with response;
});
Reference http://api.jquery.com/jQuery.getJSON/
In reference to your last comment use this format.
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){});
});
Update
Just remembered this bit, If you have control over both servers are you sending JSONP responses? If this is your JSON data
response = { status:'success', message:'Successfully created object'}
To send it as JSONP you must wrap it up in a function(). Like
jsoncallback + "(" + JSON.stringify(response) + ");";
What this does is it executes the function generated by Jquery (this is done internally when specifiy callback=?. You can get the value by checking localhost:3001 logs) and passes your JSON data as parameters to that.
So if on the server side you are not generating JSON-P response it wont work.

We ran into a similar issue once long back, although with json, not jsonp. And it wasn't a cross-domain problem. Counting on my memory, I believe we had to remove respond_to from the controller and provide :status => 200 to render method to get it working. I'm not very sure, but you could give it a shot.

Related

Rails 5: Respond to AJAX call with HTML (instead of javascript)

(Rails version 5.1.2)
I would like to respond to AJAX with HTML rather than javascript for much the same reasons as outlined in this stack overflow question.
However, I can't actually get it to work.
I'm using form_for with remote: true to send the request via AJAX. Note that I've also experimented with data: {type: :html}.
My controller action has the line render layout: !request.xhr? and has an associated view. It's this view that I want sent back to the client.
Yet the client-side code:
$("form").on('ajax:success', (e, data, status, xhr) ->
console.log xhr.responseText #using console.log data produces same result
)
Gives:
Turbolinks.clearCache()
Turbolinks.visit("http://localhost:3000/...", {"action":"replace"})
Where's the HTML?
Unless I am completely misunderstanding what you want to do, this should be what you are looking for:
Javascript:
$.ajax({
// remember to add this route to your routes file
url: "products/ajax_render",
success: function(data){
$('.some_div').html(data['html'])
},
});
Ruby on Rails:
def ajax_render
# render some view and store it in a variable
html = render "products/your_view"
# return it inside the json response
render json: { html: html }
end
Am I missing something?

How to do an ajax request with large parameters?

I am getting 'Request-URI Too Large' error when I tried to call a rails controller function from javascript with a large json parameter. I'm using Webrick http server. Is there any way to resolve this without changing the server?
I have something like:
$.ajax({
url: 'application/get_list',
data: { options : options_json, selected_option : selected_option_string},
success: function(data) {
// Insert the data to a div (returned data is a select tag with options)
},
type: 'get'
});
The simplest fix would be to change it to a POST request, and set up the action to handle that, and then you won't run into this error.
If you need to it to be a GET request, you can add a file called webrick.rb to the config\initializers directory with this content:
if defined?(WEBrick::HTTPRequest)
WEBrick::HTTPRequest.const_set("MAX_URI_LENGTH", 10240)
end
and if you keep getting the error, keep increasing the number 10240 until it works.
Since your comment says it needs to be a GET request, you really have no option but to set the MAX_URI_LENGTH. From the WEBrick source:
if #request_line.bytesize >= MAX_URI_LENGTH and #request_line[-1, 1] != LF
raise HTTPStatus::RequestURITooLarge
end
If you need really long URI's, then set it to something absurd, like 9223372036854775807

AJAX call error - status of 400 (Bad Request)

I'm trying to use the BloomAPI to retrieve Doctor's NPI number by querying with their first and last name. I'm using Jquery Ajax to make a get request for the JSON data.
I am able to get the JSON data when I do CURL in the terminal: curl -X GET 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN'
For the purpose below - I just hardcoded in the params into the URL.
I get a "Failed to load resource: the server responded with a status of 400 (Bad Request" Error. Any idea what I might be doing wrong?
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp'
}).done(function(server_data) {
console.log(server_data)
}).fail(console.log("failed"));
This was a weird one... your code is actually basically correct, however, it appears bloomapi does not support disabling caching in the way jquery does it.
When you make the jquery call you have, the actual url becomes something like this:
http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN&callback=jQuery111207365460020955652_1428455335256&_=1428455335257
The callback is a jsonp construct, and the _ is a way of breaking caching. However, bloomapi appears to not like this:
jQuery111207365460020955652_1428455335256({"name":"ParameterError","message":"_ are unknown parameters","parameters":{"_":"is an unknown parameter"}});
To get around this, you can disable cache busting like so:
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp',
cache: true
}).done(function(server_data) {
console.log(server_data)
}).fail(function() { console.log("failed") });
You will have to be careful of how else you break the cache if that's an issue; the api provider may be able to provide feedback on how to do this.
In the future, you can easily check the errors you are receiving/what you are sending using a web debugger; I used Fiddler to figure this out.

AJAX Post to store JSON with Python and javascript

I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.
Python
mainPage = """
<html>
html is included in my python file.
</html>
"""
class JSONInterface(webapp2.RequestHandler):
def post(self):
name =self.request.get('name')
nickname =self.request.get('nickname')
callback = self.request.get('callback')
if len(name) > 0 and len(nickname) >0:
newmsg = Entry(name=name, nickname=nickname)
newmsg.put()
if len(name)>0:
self.response.out.write(getJSONMessages(callback))
else:
self.response.out.write("something didnt work")
def get(self):
callback = self.request.get('callback')
self.response.out.write(getJSONMessages(callback))
This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.
Javascript
$(document).ready( function() {
$("#post").bind('click', function(event){
var name = $("#name").val();
var nickname = $("#nickname").val();
postData = {name: name, nickname: nickname, callback: "newMessage"};
$.ajax({
type: "POST",
url: "http://localhost:27080/json",
data: postData,
dataType: "json",
done: function() {
// Clear out the posted message...
$("#nickname").val('');
},
fail: function(e) {
confirm("Error", e.message);
}
});
// prevent default posting of form (since we're making an Ajax call)...
event.preventDefault();
});
The Javascript for the post
Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.
Did you ask the same question yesterday and then delete it? I swear I just answered the same question.
You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.
data: JSON.stringify(postdata),
HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.
For starters, the ajax call is pretty close. The full path
"http:://localhost:27080/json"
is not necessary, the relative path will work, but that is not the problem.
Your callback, as it stands, will work as 'success':
success: function(response) {
alert(response);
// Clear out the posted message...
$("#nickname").val('');
}
However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:
$.ajax({
type: "POST",
url: "/json",
data: postData,
dataType: "json"
}).done(function(data){
console.log(data);
});
Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.
import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
name = self.request.get('name')
logging.info(name) ## will print the value of 'name'
Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter.
In your python code:
import json
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
callback = self.request.get('callback')
logging.info(callback) # will print correctly
self.response.out.write(json.dumps(callback))
Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

Categories