Angularjs Service performing a POST request randomly gets cancelled - angularjs

I have a service that makes a simple POST:
saveVersion: function(styleGuideId, data){
return $http({method: 'post', url: '/style_guides/' + styleGuideId + '/new_version', data: data}).then(function(project){
console.log('request completed')
});
},
In the console, if I fire this request, it works fine.
But when I click a button in my ui that makes this request, I see on my server the request gets completed with a 200 but on the client side the browser says it is cancelled.
The extra GET is also a mystery. In the console, I trigger the request like this:
angular.element(document.body).injector().get('StyleGuides').saveVersion(sg_id, data)
//sg_id and data are local variables that I got like this:
sg_id = angular.element($0).scope().project.style_guide_id

Just figured it out. Stupid Mistake
The button that triggers the save looked like this:
Save
See the typo? changing javacript:// to javascript:// fixed the issue.

Related

angularjs custom REST action and error handling

I'm having some trouble with error handling in a little angularjs application. I'm interacting with a Flask backend and a Postgres DB.
I have a factory service
appointServices.factory('Appointments', ['$resource', function($resource){
return $resource(someUrl, {}, {
query: { ... }
,
create: {
method: 'POST'
,url: 'http://somedomain:port/new/:name/:start/:end/:treatment'
,params: { start: '#start', end: '#end', name: '#name', treatment: '#treatment' }
,isArray:false
}
});
}
]);
Inside a controller I'm making the following call
Appointments.create($scope.appointment, function(value, responseHeaders) {
// success handler
console.debug('success: ', JSON.stringify(value));
}, function(httpResponse) {
// error handler
console.debug('error: ', JSON.stringify(httpResponse));
});
Here $scope.appointment contains the relevant parameters for the create action.
Now, in the backend I'm able to catch DB errors involving constraints and I'm trying to return an error code with a 'meaningful' message. So I have a python method
def create(name, start, end, treatment):
try:
...
transaction_status = 'ok'
code = 200
except IntegrityError as e:
...
transaction_status = 'IntegrityError'
code = 500
finally:
...
return make_response(transaction_status, code)
Everything works fine, I'm able to talk to the backend, create new data and insert this in the DB. As I said, any violation of the constraints is detected and the backend responds
curl -X POST "http://somedomain:port/new/foo/bar/baz/qux" -v
...
< HTTP/1.0 500 INTERNAL SERVER ERROR
...
IntegrityError
So, the problem is, no matter whether the action create was successful or not, the intended error handler specified inside the controller is always fired. Moreover, I always end up with a status code 404 in the httpResponse. Firebug shows correctly the code 500 as above, though.
Anybody has any idea of why I'm getting this behavior?
Any suggestions on how to improve the error handling mechanism are also welcome.
Thx in advance.
P.S. Following the documentation on $resource I have also tried variations on the factory service call, e.g.
Appointments.create({}, $scope.appointment, successCallback, errorCallback);
Appointments.create($scope.appointment, {}, successCallback, errorCallback);
with the same results.
Update:
Forgot to mention the important fact that I'm interacting with the backend via CORS requests. The POST request in create above is having place with the OPTIONS method instead. As I mentioned everything is working correctly except for the error response.
Under further investigation, I tried to isolate the factory service, in case I did something wrong, and I also tried the approach shown in the credit card example ($resource docs), but with no positive result.
However, I came up with two workarounds. Firstly, I was able to create a plain JQuery POST request, as in the example shown in the docs. This time, the request is not replaced by OPTIONS and I got the error code correctly.
I also managed to connect to the backend with the low-level $http service as follows:
var urlBase = 'http://somedomain:port/new/:name/:start/:end/:treatment';
var url = urlBase.replace(/:name/g, $scope.appointment.name);
url = url.replace(/:start/g, $scope.appointment.start);
url = url.replace(/:end/g, $scope.appointment.end);
url = url.replace(/:treatment/g, $scope.appointment.treatment);
// force method to be POST
var futureResponse = $http({ method: 'POST', url: url });
futureResponse.success(function (data, status, headers, config) {
console.debug('success: ', JSON.stringify(data));
});
futureResponse.error(function (data, status, headers, config) {
console.group('Error');
console.debug(JSON.stringify(status));
console.debug(JSON.stringify(data));
console.groupEnd();
});
This time, as in the case of JQuery, the request is done effectively with POST and error codes are correctly received.
Notice also that I'm not calling $http.post but I set the method to POST as part of the object parameter to $http, otherwise the connection takes places with OPTIONS as before.
Still trying to figure out what is happening with $resource.

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.

destroy always returns with the error callback (although everything seems to be ok)

I'm trying to delete a model on my backend and what I do is this (the code is adapted just to show you the issue, some parts could be missing):
attending= new Backbone.Model();
attending.url= this.url() + "/reject";
attending.set({
id: this.id
})
attending.destroy({
success: function(){
alert("yes");
},
error: function(){
alert("no");
}
});
but what I always obtain is a "no" alert. The fact is the backend seems to be updated correctly and what I obtain as a response too. Here it is:
so... what's wrong with the response I get? Why doesn't backbone recognizes it as a successful response? I get 200/OK and a "application/json" format as well!
Your backend should return something with 200
jQuery expect 200 with application/json to have some content
Have a look here: https://github.com/jashkenas/backbone/issues/2218#issuecomment-20991938
You might want to place a "debugger;" in the error callback and trace exactly why its coming that route vs the success route. That should atleast get your started on the right path...

extJS 3.2.1 AJAX request while refreshing other lists

I have a grid control which I reload via a timer every second or so. I initiate this timer immediately before calling a AJAX request which is long processing at times.
The grid I am refreshing is actually a list of tasks to be carried out on the server.
I am trying to give the user some ideas as to how much longer they have to wait.
this code:
var task = {
run: function(){
Ext.getCmp("id_task_approval_progress").store.reload();
},
interval: 1000
}
var runner = new Ext.util.TaskRunner();
runner.start(task);
Ext.Ajax.request({
url: 'services/index.php/application/task/approve',
params: { id_primary: id_task, id_status: status },
success: function(response, action){
if(!ajax_error_handler(response, action)){
window.location.reload(true);
}
}
});
Does not work...it prevents the grid from refreshing until the AJAX request is complete???
Using ExtJS 3.2.1 - what am I doing wrong? Is there a work around or setting?
Regards,
Alex
I think that several requests were sent to server and the issue isn't related to the client side (apache config or how php works with sessions). If yes - please check this link.

submit changes on extjs roweditor grid

I have a grid what update my database (via PHP) with JSON record.
I want to know, how the data writed - record or not. I have an answer from PHP (true or false) to the grid, but dont know how to use it. How my grid can use this answer? (success event?)
Now, for example, User added new record without id at database (and i need this id for the future update), php answer what record saved(true) and told me id of new record. How I should work with it?
And I saw somehere some beauty flowing from the top of screen windows - how do the called?
Sorry for typically questions, but I cant find answer for it.
Thanks.
If you are using Ext.Ajax.request to make the connection this is how you do it.
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
There is a success callback function you specify which gets the response from the server which is a JSON object. This is where you can send things back and then manipulate your roweditor grid however you like.
Success also doesn't mean that everything went ok, it just means the request did not produce an html error code 4xx or 5xx.
The failure callback function is what to do if the server returns an error code for the AJAX request.

Resources