Retrieving JSON from an external API with backbone - ajax

I'm new to backbone.js and I've read other solutions to similar problems but still can't get my example to work. I have a basic rails api that is returning some JSON from the url below and I am trying to access in through a backbone.js front end. Since they are one different servers I think I need to use a 'jsonp' request. I'm currently doing this by overriding the sync function in my backbone collection.
Api url:
http://guarded-wave-4073.herokuapp.com/api/v1/plans.json
sync: function(method, model, options) {
options.timeout = 10000;
options.dataType = 'jsonp';
options.url = 'http://guarded-wave-4073.herokuapp.com/api/v1/plans.json'
return Backbone.sync(method, model, options);
}
To test this I create a new 'plans' collection in my chrome console using "plans = new Plans()" and then "plans.fetch()" to try and get the JSON.
When I call plans.models afterwards I still have an empty array and the object that returns from plans.fetch() doesn't seem to have any json data included.
Any ideas where I'm going wrong?

I have had the same problem before. You should not have to override your sync method.
Taken from Stackoverflow Answer
"The JSONP technique uses a completely different mechanism for issuing HTTP requests to a server and acting on the response. It requires cooperating code in the client page and on the server. The server must have a URL that responds to HTTP "GET" requests with a block of JSON wrapped in a function call. Thus, you can't just do JSONP transactions to any old server; it must be a server that explicitly provides the functionality."
Are you sure your server abides to the above? Test with another compatible jsonp service (Twitter) to see if you receive results?

Have you tried overriding the fetch method as well?

You should add ?callback=? to your api url in order to enable jsonp

Related

Load data from ajax request (json) on startup in AngularJs

I have this simple page that just needs to show contents that is loaded from an external url (ajax request, response in json format)
I should say I'm a AngularJS newbie.
I've googled a bunch and found different ways of doing this and couldn't manage to determine which is the correct/simple/up-to-date way to achieve this.
My 2 challenges -
Making the AJAX request run on startup (I can load the page before that happens and just load the contents one the ajax request finishes. Maybe show a 'Loading..' indicator)
Doing a ajax request correctly.
Here is my attempt. I know that the ajax request is never made because its not setup correctly.
You are getting into .error function:
http://jsbin.com/oDUsuVA/3/edit
For jsonp your response should be something like:
callback([
{
"title":"License Title 1",
"licenseUrl":"http://cnn.com",
"licenseText": " test"
}]);
Edit:
You can simply do .get() request too, but if you had to use jsonp request interface, you would have to correct response.
A Jsonp request always wraps the logic into a json callback wrapper function.
I just did $http.get instead of your $http.jsonp and it did work for me.

HTTP GET request with a separate entity body in JMeter?

I want to send a JSON payload with HTTP GET request but I want to prevent it to be viewable in URL.
GET http://<domain>/school/search.json
{
schoolId: ["S1","S2","S3"],
location: "Pune"
}
How can I achieve this in JMeter Apache?
Get implies visible in Url, what exactly do you want to do ?
Sending Body data along with HTTP GET request is available for default (HttpClient4) implementation since ver.3.1 (as Bugzilla #60358), as well as request retrying behavior both for PUT and GET with body fixed since ver.3.2 (as Bugzilla #60837).
Just as additional note: you will likely encounter problems if you have cache/proxies in your setup and if you plan to take advantage from their usage.

Retrieving XML data from a ReST service across domains with Dojo

I am trying to write a browser-based Javascript client for a ReST application which responds with XML (so it seems JSONP is out of the questions).
I am trying to retrieve the data using dojo.io.script.get but the parameter that is passed to the callback function is an object from which it seems I cannot retrieve the XML data of the response.
dojo.io.script.get({url:"http://enterpriseapp.enterprisedomain/path/to/rest/collection",
load:function (data) {
// 'data' does not contain the actual response (which is XML)
}
});
What is the correct way to retrieve this data?
The dojo.io.script.get method will inject a <script> from the specified web address. The data content from this script will be passed to your load function; hence, the content must validate as Javascript. You can't load XML into a script tag.
If you want to load XML, you'll need to use dojo.xhrGet; however, this will not allow requests to 3rd party urls. The advantage of using dojo.io.script.get is that you can use different origin address' than the page loading them.
dojo.xhrGet({
handleAs: "xml",
load: function(dom){
// do something with the DOM XML object
},
error: function(error){
}
});
See: dojo.xhrGet Documentation
If you are trying to load the XML from another website it's a bit of a dead-end. You can use the Access-Control-Allow-Origin header if you have access to the sending server.
Another solution that I have used is to write a proxy script (in PHP or other server language) to mirror the XML on the correct domain. You'll need to be careful if you do this to include good checks so that your server code is not abused by someone for proxying.
See the following Stackoverflow conversation for more about Access-Control-Allow-Origin:
jQuery XML REST Access-Control-Allow-Origin

Cross domain javascript ajax request - status 200 OK but no response

Here is my situation:
Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :)
The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server.
This is the code im using:
var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&mail=mymail#site.net";
http.async = true;
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//do my things here
alert( http.responseText );
}
}
http.send(params);
In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.
When i check the ajax responnseText I always get a Status:0
Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this?
Thanks..
Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function receiveData(data) {
// ...
}
And then your server wraps JSON data in a function call, like this:
receiveData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
You're going to need to have your response sent back to your client via a JSONP call.
What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.
Lots of steps involved. Using a library like jQuery provides a lot of support for this.
Hope this helps.

Comet, Tomcat and READ events

Trying to get my way trought Comet with Java servlets, I encountered a big problem: There seems to be no way to use the established connection to the client to send the server additional data from the browser (works in plain java when writing to the inputstream).
Following problem arises for a CometChat application when a Client connects to servlet, receives a form for sending input and a form for presenting server output: Now if the client wants to send some data at this connection, resulting in a READ event at the servlet, how can this be done?
I tried sending GET, HEAD and POST. With HEAD the comet connection is closed afterwards. GET always produces END, BEGIN and POST produces BEGIN, READ.
I tried searching the web, but the only answer I found was: Comet READ events are generating when there is a POST method with a body
How can I achieve this?
I'm using plain Javascript Ajax:
function send(content) {
var text = document.controller.input.value;
params = 'input=' + content;
var ajaxObj = createXMLHttp();
ajaxObj.open('POST', 'CometChat', true);
ajaxObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxObj.setRequestHeader('Content-Length', params.length);
ajaxObj.setRequestHeader('Connection', 'close');
ajaxObj.onreadystatechange = function() {};
ajaxObj.send(params);
}
This produces BEGIN, READ. What headers do I need to set to produce a solely READ event only?
I'm able to 'cheat' this by looking up my connections and reuse response, but on client side, the AJAX request stays in interactive mode (although flushing it on the server) and I'm only able to may 5 requests on FF and 10 requests on IE before the following request is not processed. Also as soon as the first AJAX request is received on the server, I'm get TIMEOUT events, two per request repeating forever.
What's the real way?
Good luck, creating a Comet app with Java Servlets is a pretty complicated undertaking. Plus Tomcat wasn't really designed for it. I suggest you check out StreamHub Comet Server.
As rajax says, developing a Comet app in servlets is a really bad idea.

Resources