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.
Related
Hi I'm trying to update my database with function that returns a number
$scope.sum = function()
{
return $scope.inp + $scope.points;
};
this function will update the record in object points, column name and id 1:
$scope.addPoint = function() {
PointService.addPoint($scope.sum, 1)
.then(function(result) {
$scope.inp = 0;
getMyPoints();
});
}
addPoint = function(id,points)
{
return $http.put(getUrlForId(1),points,name);
}
the error is: Error details: Cannot convert type 'int' to 'System.Collections.Generic.Dictionary'
the data type of the field is Float.
Any idea what is wrong with the code?
you are passing function reference to PointService.addPointer(),
use this:
$scope.addPoint = function() {
PointService.addPoint($scope.sum(), 1) // NOT PointService.addPoint($scope.sum, 1)
.then(function(result) {
$scope.inp = 0;
getMyPoints();
});
}
this will execute your function and pass the output (id parameter) to addPoint function, further, for more safe side, you can return Number from $scope.sum() i.e.
$scope.sum = function()
{
return Number($scope.inp + $scope.points);
};
This looks like an issue with how you're contacting Backand. You use the following code to send your points over:
addPoint = function(id,points)
{
return $http.put(getUrlForId(1),points,name);
}
This is an older version of calling the Backand API that is manually constructing a PUT request, and putting "points" and "name" as the "Data" and "config" parameters to $http. With an object update via PUT, you'll need to provide the updates as an object. So if you wanted to update the points and the name of the object (and I'm doing some assuming based upon what I can tell from the code snippet above), you'd need to encapsulate these properties in an object that has the following general format:
{
"field_name_1":"new value_1",
"field_name_2":"new value_2",
etc ...
}
This should then be sent as the body of the request. So, for your code, change it to the following and see if this helps:
addPoint = function(id,points)
{
return $http.put(getUrlForId(1),{points: points, name: name});
}
To give more info on why you're seeing this particular error, Backand is depending on this JSON format in the body. Our platform should definitely do more validation (and I'll create a ticket for the devs to handle non-conforming input more gracefully), but at the moment we simply take the body of the request, convert it to a dictionary object, then begin the requested operation. As your code above sends only "1.0" as the body, this fails the conversion into a dictionary, causing the stack exception and the issue you are seeing.
As a note, we offer a new SDK that encapsulates these HTTP methods, performing the authentication header generation and HTTP messaging for you, providing promises to handle responses. You can find it on our Github page at https://github.com/backand/vanilla-sdk. To make the same call using the new SDK, the code would resemble the following:
backand.object.update("your object name", 1, {name: name, points: points})
.then(function(response){
console.log(response.data);
});
I am getting an error "syntax error JSON parse unexpected end of data at line 1 column 1 of json data". The RESTful service is runnning, a straight test returns valid json data (verified at http://jsonlint.com/)
[{"id":2,"name":"Flourescent Penetrant Inspection","description":"The fluorescent penetrant inspection process.","abbreviation":"FPI","tempId":null,"processType":"INSPECTION","indicationTypes":[{"id":1,"name":"Crack","description":"An identified crack on the piece.","abbreviation":"","tempId":null,"groupName":"","markupType":"LINE","useSizeDescription":true,"sizeDescription":"<= 1 in.::> 1 in.","rejectReason":"Crack","defaultDisposition":"MRB"},{"id":2,"name":"Inclusion","description":"An identified inclusion on the piece.","abbreviation":"","tempId":null,"groupName":"","markupType":"DOT","useSizeDescription":false,"sizeDescription":"","rejectReason":"Inclusion","defaultDisposition":"REWORK"}]},{"id":4,"name":"CMM","description":"The CMM process.","abbreviation":"CMM","tempId":null,"processType":"INSPECTION","indicationTypes":[]}]
The error in the HTTP response, yet it is returning a 200 message. The angular app is seeing it as an empty array. Any ideas?
The applicable part of the Controller is:
indicationTypeController.constant("indicationTypeUrl", "http://localhost:8080/services/api/indication-types.json");
indicationTypeController.controller('indicationTypeController', function ($scope, $http, $resource, indicationTypeUrl) {
$scope.indicationTypeResource = $resource(indicationTypeUrl+":id", { id: "#id" },
{ 'create': {method: "POST"}, 'update': {method: "PUT"}
});
$scope.listIndicationTypes = function () {
$http.get(indicationTypeUrl)
.success(function(data){
$scope.indicationTypes = data;
});
//$scope.indicationTypes = $scope.indicationTypeResource.query();
}
. . . .
As you can see I am currently using a $http.get, I also tried a query().
Any
Usually, the $http promise returns an object that contains the headers and the data. In your success handler for the $http, you have
$http.get(indicationTypeUrl)
.success(function(data){
$scope.indicationTypes = data;
});
I'm pretty sure that data is the full response and you need to get the specific data by using the data property of this object. Therefore, this would become the following:
$http.get(indicationTypeUrl)
.success(function(data){
$scope.indicationTypes = data.data;
});
In other implementations, instead of the passed in parameter being called data, it's usually called result, so that you can reference the contained data like result.data instead of data.data
The other thing to make sure of is that the Content-Type is set appropriately between the server and client. If it's not application\json you'll probably run into issues.
This is an CORS issue, please add the following to the response header, before sending the result.
"Access-Control-Allow-Origin" : "*"
For instance, if you are using play server (Java code) to serve the request, the following statement should be added to the method where you are returning the data from
response().setHeader("Access-Control-Allow-Origin", "*");
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){}
I am using a service to return list of files. This service returns following.
Success case: List of file object in json format as given below with HTTP code as 200
[{"_id:"3453534","name":"File 1"},{"_id:"5756753","name":"File 2"}]
Failure case: This returns error response with error message as HTTP error code 500.
{errorMessage: "No files found for ptoject id 522b9358e4b0bab2f88a1f67"}
I am using following "query" method invoke this service.
//get the new value of files as per changed project id
scope.files = ProjectFile.query({ projectid: scope.project._id }, function (response) {
//Check if service response is success/fail
if (response.servicestatus != undefined) {
//this is error case. Show error message.
alert("Failed to load list of files for this project: " + response.errorMessage);
}
else {
//update scope
scope.files = response;
}
});
Problem I am facing is response object which is converted by $query() method. I am getting response as an array which seems incorrect. Not sure why $query() is also expecting error response as array. In error case; I am getting response as array as below
response[0][0]="N";
response[0][1]="o";
response[0][2]="";
response[0][3]="f";
response[0][4]="i";
response[0][5]="l";
response[0][6]="e";
response[0][7]="s";
....
....
I am not sure why $query() is behaving like this. Not sure how to handle it in correct way. Please help.
The query method of $resource expects the response as an array by default. The query isn't failing, but the response from the server isn't providing what query() is expecting.
If you know that only "no files" responses will not be arrays, then you can check to see if the response type is an array in order to know whether anything has been found or not.
This answer outlines an easy way to check:
scope.files = ProjectFile.query({ projectid: scope.project._id }, function (response) {
//Check if service response is success/fail
if (response.servicestatus != undefined) {
//this is error case. Show error message.
alert("Failed to load list of files for this project: " + response.errorMessage);
}
else if ( Object.prototype.toString.call(response) === '[object Array]' ) {
scope.files = response;
} else {
//handle the lack of files found
}
}
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)