Backbonejs simplest collection fetch - javascript

I'm trying to download, parse and show a list, from the XML received from my server using Backbone.js. The code is like:
var Item = Backbone.collection.extend({
url: "http://myurl.com/file.xml",
parse: function() {
console.log("parse");
},
success: function(data) {
console.log(data);
},
error: function() {
console.log("error");
}
});
var View1=Backbone.view.extend({
initialize: function() {
var item = new Item();
item.fetch();
}
});
When I check it in the Chrome extension, the XML file is getting downloaded but the breakpoints placed in the parse, success, error directly lands to the error.
And it has 3 arguments, but I'm unable to extract any information from that.

Backbone does not support fetching XML, hence, you'll need to override the sync method to provide your own custom parsing functionality. If you don't want to have to mess with Backbone internals, try doing your $.ajax GET first, parse your response into a proper JSON Array and then use that array with a Backbone#Collection-reset.
Backbone#Collection-fetch
The server handler for fetch requests should return a JSON array of
models.
Backbone#Sync
With the default implementation, when Backbone.sync sends up a request
to save a model, its attributes will be passed, serialized as JSON,
and sent in the HTTP body with content-type application/json. When
returning a JSON response, send down the attributes of the model that
have been changed by the server, and need to be updated on the client.
When responding to a "read" request from a collection
(Collection#fetch), send down an array of model attribute objects.

Related

How do you modify the body content of the response associated with an upload request in fineuploader?

I am currently using FineUploader to upload a file using the uploader.uploadStoredFiles() method. Using a network packet analyzer, I observe once the upload request has been sent, a JSON response is returned containing success=true or success=false property among many other properties.
Under normal conditions, this JSON response is parsed in Javascript and dealt with appropriately. However, I wish to add a custom attribute (something like "mycusattr", "my custom value") to the JSON structure, so that I can parse it with all the attributes in Javascript like I normally do.
Does anyone know where the JSON structure in an upload response is defined, and if so, can I add one more custom attribute to it?
You may return whatever properties you'd like from your server in your JSON response, and they will be made available to you in your onComplete callback handler. For example, suppose your response, in addition to "success": true, contains a "foo" property with a value of "bar". You can access this property as follows:
var uploader = new qq.FineUploader({
/* ... other init options ... */
callbacks: {
onComplete: function(id, name, response) {
console.log(response.foo) // prints "bar"
}
}
})

Get jQuery $.ajax to send data in body for GET [duplicate]

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

Loading JSON from Dojo JsonRest into object variable

According to this post Remove String from JSON, I want to fill a Dojo Selectbox with JSON Data. The Problem is that I have to change the JSON Data before I can handout the data to the dijit.form.select Box.
I get the data via JsonRest. The question if, how I can load the Json Data into a normal object variable? I tried this here but it did not work.
var processStore = new JsonRest({
target: "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit",
headers: {"Authorization": "Basic a2VybWl0Omtlcm1pdA=="},
allowNoTrailingSlash: false
});
var processes = processStore.query("",{});
I simply want to load the JSON data from the JsonRest store in a normal variable.
Thank you
The JsonRest store only accepts an array, so you're not able to retrieve the data, because your store is not able to read that data for you.
If you're only interested in reading the data (so no updating/creating/deleting has to be done), the easiest way is to retrieve that data using an AJAX request and manually put it inside a dojo/store/Memory store, for example:
require([ "dojo/request/xhr", "dojo/store/Memory" ], function(xhr) {
var url = "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit";
xhr(url, {
handleAs: json
}).then(function(data) {
if (data.data !== undefined) {
var myStore = new Memory({
data: data.data
});
// Do something with "myStore"
});
});
If you're interested in the full capabilities of the JsonRest store, you will have to extend it by yourself. If you look at the code you can see several AJAX requests, in:
get()
put()
remove()
query()
Now you can write your own store and extend those methods.

Need to get serialized data from a form

I'm new to prototypejs. Can you guys tell me how to get serialized values from a posted form using Ajax in prototype?
http://www.prototypejs.org/api/ajax/request
Is this what you need?
http://prototypejs.org/api/form/serialize
Or you want to handle a form through ajax instead of page load? then
http://prototypejs.org/api/form/request
"how to get serialized values from a posted form using Ajax " Makes it sound like you're expecting the Ajax response to include the serialized data sent to the server, but what the response contains is entirely up to the server. Typically, once you make an Ajax request, the onComplete handler doesn't really care about the properties that it sent. The response argument to the onComplete (and any other Ajax callback) contains a request property, which contains parameters object. This would be useful if you did indeed need to see what your request sent to the server, like so:
$('customerdetails').request({
method: 'get',
onComplete: function(response) {
console.log(response.request.parameters); // What you sent to the server
console.log(response.responseText); // What the server sent back to you
console.log(response.responseJSON); // JSON-ified version of what the server sent back
}
});
It's possible for response.responseJSON to be null if Prototype isn't sure that the response actually contains JSON (if, for instance, the response headers were improperly set). If you can bank on the response being JSON, you could do something like this:
onComplete: function(response) {
var jsonObj = response.responseJSON || response.responseText.evalJSON();
// now you can work with jsonObj
}
Hope this helps and I didn't just completely misunderstand your question.
new Ajax.Request('your_ajax_url',{
method:'POST',
parameters:Form.serialize($('your_form_id'))
});

POST JSON *in Request Body* using MooTools

I'm trying to post JSON between URLs in my app. The receiving URL expects JSON in the body of the request and responds with JSON in the body of the request. The problem is I can't seem to send JSON in the body using Mootools Request.JSON. This is what I have:
// formObj is an object constructed from a form
var request = new Request.JSON({
url: "/api/object.new",
urlEncoded: false,
onRequest: function(){
// swap submit button with spinner
},
onComplete: function(jsonObj) {
// work with returned JSON
},
body: JSON.encode(formObj)
});
request.setHeader("Content-Type", "application/json");
request.post();
The server returns a 500 error:
BadValueError: Property name is required
Which means that request.name is returning None which means that the server is not getting my JSON.
Using HTTPClient to paste the output of JSON.encode(formObj) into the body field produces the desired results.
body is not a valid mootools property for Request. use data: blah instead. as it stands, data is empty so no wonder you get nothing on the server side...

Categories