BackboneJS model.fetch() unsuccessful - backbone.js

Hi I have this model :
window.shop = Backbone.Model.extend({
initialize: function () {
console.log('initializing shop');
},
urlRoot: "shopData.json",
});
and then i go :
var myShop = new shop();
myShop.fetch({
success: function (model, resp){
console.log(resp);
},
error: function (model, resp){
console.log("error retrieving model");
}}, {wait: true});
now I'm always getting the error message - never reaching success :-(
thanks for any help.

Edit 1:
As per your comment the server is sending the proper response but Backbone is still calling the error function. Add the following line at the beginning of the error callback:
error: function (model, resp){
console.log('error arguments: ', arguments);
console.log("error retrieving model");
}
The first line should print an array of objects. The first element in the array should the jqXhr object, the second should be a string representation of the error. If you click on the first object, the dev tools will let you inspect its properties. Read up on the properties of the object here http://api.jquery.com/jQuery.ajax/#jqXHR.
Using that information you can verify if the jQuery is receiving an error from the server.
If there is no server side error, then check the value of the responseText property. That holds the string data returned from the server. $.ajax will try to parse that data into JSON. Most likely the parsing is throwing an error and the error handler is being raised instead.
Copy the response text and paste it into http://jsonlint.com/. Verify that the response sent from the server is valid JSON. Do update your question with the output of the console.log statement and the responseText property of the jqxhr object.
-x-x-x-
You seem to be using the model independently. As the per the documentation, http://backbonejs.org/#Model-url,
Generates URLs of the form: "/[urlRoot]/id"
That means, you are making a request to shopData.json/id. Also, you haven't specified the id.
Insert a console.log(myShop.url()) before the myShop.fetch(). Let us know whats the output. Also, possibly share the details of the ajax request as seen in Firebug or Chrome Dev Tools. I am interested in two things, the request url and the response returned by the server. (http://getfirebug.com/network)

Related

what does Restangular.all() return?

Why do we have to use Restangular.all every time before making a request.
var messages= Restangular.all('posts');
var newMessage = {
body: "Hello world"
};
messages.post(newMessage);
When I view 'messages' in console it shows an empty array.
1)What are the properties of 'messages'?
2)Is it an instance of collection.
From the documentation: messages is just a restangular object which points to your messages resource uri on the server.
In order to see the messages you would need to call a method on messages such as getList() this will return a promise which you would then unwrap to find your list of messages.

Unable to run a fetch operation in backboneJS

Here's a fetch operation I've written in a view:
this.collection.fetch ({
data:{
values: 100,
type: "normal"
},
success:(collection, response) => {
_.each(collection.models, (model) => {
Log.show(model.get("question"));
})
},
error: (err) => {
Log.error("couldn't receive data");
}
});
My Webstorm throws an error on fetch({}) that says Supplied Parameters are incorrect
I'm not able to find any other api specification for the fetch call. The code is in and the typescript definition for backbone I'm using is here:
https://github.com/borisyankov/DefinitelyTyped/blob/master/backbone/backbone.d.ts
UPDATE==
The result I see in the log is this:
Triple
Triple
Triple
Triple
Triple
Here "triple" is the value of the "question" attribute in the last model added to the collection. There are 5 models in the collection (in the persistent) database and if there were 6 it would display "Triple" 6 times. There is some problem in the API call I made to get the value of the question object
I'm probably not calling the function right. I need to know whats the appropriate call for getting the value of an attribute from the model. Or this could be a problem actually retrieving the values from the server.
I've tried the following to actually get the right value in the log:
Log.show(model.toJSON().question);
Log.show(model.toString());
Log.show(model.question);
The success callback should look like this:
success:function(collection, response){}

Backbone model's fetch doesn't work when the page initially loads but on second attempt works fine

In my backbone project I am trying to fetch a model based on some search criteria submitted by the users from a form. In submit handler, I am trying to fetch the model by passing search criteria's via data option (following is the code).
var productType=$("#productType").val();
var customerId=$("#customerId").val();
var stateSelected=$("#selectedState").val();
var srbStatus=$("#stateReportingStatus").val();
var dateType=$("#dateType").val();
var fromDate=$("#fromDate").val();
var toDate=$("#toDate").val();
var billTypeInd=$("#billTypeIndicator").val();
var dataElement=$("#dataElement").val();
var ediFileName=$("#ediFileName").val();
var ediBillName=$("#ediBillNumber").val();
var billId=$("#billId").val();
var claimantFirstName=$("#claimantFirstName").val();
var claimantLastName=$("#claimantLastName").val();
var insurerName=$("#insurerName").val();
var insurerFEIN=$("#insurerFEIN").val();
var insurerZip=$("#insurerZIP").val();
var dashboardSearchResultModel= new dashboardSearchResult();
var dashboardSearchResultModel= new dashboardSearchResult();
dashboardSearchResultModel.fetch({
data:{
productType: productType,
customerId: customerId,
state:stateSelected,
srbStatus:srbStatus,
dateType:dateType,
fromDate:fromDate,
toDate:toDate,
billTypeInd:billTypeInd,
dataElement:dataElement,
ediFileName:ediFileName,
ediBillName:ediBillName,
billId:billId,
claimantFirstName:claimantFirstName,
claimantLastName:claimantLastName,
insurerName:insurerName,
insurerFEIN:insurerFEIN,
insurerZip:insurerZip
},
wait:true,
success: function(dashboardSearchResultModel)
{
alert("This is what we get for result"+JSON.stringify(dashboardSearchResultModel));
$('#dashboardResultArea').html(self.dashboardResultTemplate({results:dashboardSearchResultModel.get("results")}));
},
error: function (model, xhr, options) {
alert("Error: An error occurred while trying to fetch the dashboardSearchResultModel");
alert("Error got model"+JSON.stringify(model));
alert("options:"+JSON.stringify(options));
alert("xhr:"+JSON.stringify(xhr));
}
});
Initially when the page loads after providing the search criteria's if I click submit the fetch doesn't work and goes to the error handler. After that when I submit the from second time the fetch works and retrieves data from the backend server. Any idea what is wrong? Thanks in advance.
When error callback is called, it is because your XHTMLRequest to the server returned a error (HTTP status code). So, there is where your problem resides.
Who starts this code? As the erros does not occur on a second attempt, I would suggest that you area callind $('#id').val() when the DOM is not ready. This way you are sending null values to the server, and that's causing the error you are receiving.
To solve your problem, assure you DOM is ready when executing this script.
See if your request is leaving the browser and reaching the server (i.e., cross-domain request fail with status 0, not reaching the server).
And, if it is, debug your server-side, as it does not seem to be an client-side problem.
So after trying many things I finally decided to try $.ajax call rather the fetch method. This is what I came up with
$.ajax({
type: "GET",
url: "rest/dashboardResult",
dataTyp: 'json',
data: {
productType: productType,
customerId: customerId,
state:stateSelected,
srbStatus:srbStatus,
dateType:dateType,
fromDate:fromDate,
toDate:toDate,
billTypeInd:billTypeInd,
dataElement:dataElement,
ediFileName:ediFileName,
ediBillName:ediBillName,
billId:billId,
claimantFirstName:claimantFirstName,
claimantLastName:claimantLastName,
insurerName:insurerName,
insurerFEIN:insurerFEIN,
insurerZip:insurerZip
}
})
.done(function(response) {
alert( "Result is: " + response);
});
This works without any problem from the get go. Now my question is how to bind the response to the backbone model?
Finally I figured out what was wrong. The call was inside a submit click handler, and $.ajax call or fetch is asynchronous. So by the time the call got reply from the server default action of submit click already took place (which is to reload the page). So by the time success or .done got called the whole page was reloaded. So I put event.preventDefault() at the beginning of handler method and let the handler receive the call back from the server and display it at the template. Thanks everyone for your time.

Error callback always fired, even when it is successful

There should be a glitch in my syntax, or something I haven't understood, but when I am doing a save method on my model. The error callback is called whatever the outcome of the method.
#new_activity = new Activity()
#new_activity.save
know: $('input#know').val()
learn: $('input#learn').val()
success: -> console.log 'success'
error: -> console.log 'error'
In my case, since I do not really know whether the new_activity has effectively passed the validation, I have to do an ugly trick to add the activity to the collection. (By the way, I do not use the create method since I do want to have the different errors, and not a simple "false".
if #new_activity.has('know') and #new_activity.has('learn')
app.collections.activities.add #new_activity
When it is successful though; there is an alert of the created model.
Edit: Further details.
Here is my model:
initialize: ->
_.bindAll #, 'validate', 'errorHandler'
#.bind 'error', #errorHandler
validate: (attrs) ->
errors = []
# We only support a certain number of languages, we enforce that the user does not select a wrong set.
if _.isEmpty(_.intersection([attrs.know], ['en', 'fr'])) is true
errors.push 'This language is not currently supported.'
if _.isEmpty(_.intersection([attrs.learn], ['en', 'fr', 'de', 'es', 'zh', 'pt', 'ar', 'ja', 'ru'])) is true
errors.push 'You cannot learn this language yet.'
if _.isEmpty(errors) is false
errors
errorHandler: (model, error) ->
console.log error
When the validation occurs, and if the validate method returns nothing, it still triggers the error event, and the error variable contains the model (but no error message).
You should check whether the new_activity is saved properly, please verify that the server returns success response to the PUT request.
Furthermore, I have had issues with using Rails 3.1 standard format.json { head :ok } because it returns a single space as a reponse and application/json as content type. Backbone then tries to parse JSON and dies with an error.
The problem is the single space that Rails sends back with head :ok. If you send back an empty string, Backbone handles it fine.
The proper way to do that is to send back a 204 No Content. You can do that by replacing head :ok with head :no_content in the format.json block. Rails will not send back anything in the HTTP body.
I'm not sure what the cause of your error is, but I think I can help you pin it down:
Looking at the annotated source for Backbone.js, you can see that save() defers to sync(), which in turn defers to jQuery's $.ajax. So ultimately, your error function (wrapped by Backbone's wrapError) is called from that.
Unfortunately, the wrapper discards all but the jqXHR argument, making debugging a bit tricky. So you might want to try hacking your local Backbone.js source file to replace the existing wrapErrorfunction with something like this:
var wrapError = function(onError, model, options) {
return function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
if (onError) {
onError(model, jqXHR, options);
} else {
model.trigger('error', model, jqXHR, options);
}
};
};
Then, at least, you'll see all of the debugging data provided by jQuery on your console.

Backbone.js getting response from server after a save()

I have a mode that saves data to a codeigniter function the codeigniter function returns valid JSON data back if it has an error how do i get the error details that the server returns when using save(). I have the following code that doesn't work
this.newproject.save({
'Objective':Objective,
"Planner":Planner,
"NISupervisor":NISupervisor,
"SiteIDs":SiteIDs,
"Status":Status ,
"StartDate":StartDate,
"EndDate":EndDate,
"Details":Details,
"PrjTitle":PrjTitle
},{
success:function(model,response){
console.log(response);
}
},{
error:function(){
alert("wrong");
}
});
Success doesn't work at all
The 2nd option to save is an object with 2 properties, success and error. I'm assuming that you mean that "error" doesn't work at all, and success works fine, based on your actual question text.
this.newproject.save({
'Objective':Objective,
"Planner":Planner,
"NISupervisor":NISupervisor,
"SiteIDs":SiteIDs,
"Status":Status ,
"StartDate":StartDate,
"EndDate":EndDate,
"Details":Details,
"PrjTitle":PrjTitle
},{
success:function(model,response){console.log(response);},
error:function(model,response){console.log(response);}
});
The error callback also passes model and response, so the response argument is what you're probably looking for.
The problem with your code is that you've got three hash arguments. The save method accepts attrs and options as its two arguments. As such, your code should look similar to this:
var attrs = {
"Objective":Objective,
"Planner":Planner,
"NISupervisor":NISupervisor,
"SiteIDs":SiteIDs,
"Status":Status ,
"StartDate":StartDate,
"EndDate":EndDate,
"Details":Details,
"PrjTitle":PrjTitle
};
this.newproject.save(attrs, {
success: function(model, response) {
console.log(response);
},
error: function(model, response) {
alert('wrong');
}
});
So your call would not have been able to attach the error function. The above example should work for you since it combines the success and error functions in the second hash argument.

Resources