Server Side Error validation - angularjs

In my application I am doing client side and server side validation. Client side validation is pretty easy and user will not be able to click on the submitForm button. But suppose the zip code entered does not match with the order number and server is giving me error in 200 response in angular $http call promise. How can I show the server side error and maintain my validation ?
{"result":{"success":false,"code":null,"message":"The entered Zip does not match with Order"},"errors":
[]

Might not be the exact answer but could help :
1) On the server side if there are errors you should first stop the script from reaching to database.
2) Populate error messages on the server side in an array in the form of associative array, which can contain field name as key and error message as value. Later send the array to client side in JSON format.
3) On the client side loop through the JSON object to initialise the scope variables that will contain error messages per field.
May be in the format : serverErrors.fieldName.error = 'Error Message from server'
This should be a scope object. And the same object should be rendered on the template per field. So that when you loop through your JSON and assign error messages to each field it will show up in template. As Angular has two way binding.
This way you will be able to handle custom server side validations and show errors on client side. And this is possible not just in theory we have implemented this approach in one of our projects.
Hope that helps :)

I think you can try
$http.post('URL', { "ID": ID }).success(function (resultData) {
if (results.result.success) {
alert("scuess!");
$window.location.href = "/";
}
else {
alert(results.result.message)
}
});

Related

Web api is giving error on passing * as the input value to the api method parameter

I am using asp.net mvc web api and i have this method
[HttpGet]
public LoginResult AuthenticateOnlineBookingUser(String userName,String password)
{
//My Code
}
The problem is that when i pass (*) as input value to the parameter (password)
i receieve this error but on other inputs it is working perfectly
A potentialy dangerous Request.Path.value was detected from client(*)
Thanks in advance
Note:My client side is written in angular js
i tried this solution as well Getting "A potentially dangerous Request.Path value was detected from the client (&)" but it is not working for me
You need to set the options for invalid characters. You can do this in your web.config as shown here.
Use url encoder to encode the request before sending it to server.
Finally solved my problem by changing my GET request to POST request The problem was with query string in Order to solve it with GET Request i have to make some changes to my query string in order to make it work but

Spontaneous Server Errors During AngularJS $http calls

I'm building an SPA in AngularJS served by a Laravel (5.1) backend. Of late I've been encountering an annoying error, a server 500 or code 0 error which is abit hard to explain how it comes but let me try to may be someone will understand the dental formula of my problem.
When i start my AngularJS controller, I make several server calls (via independent $http calls from services) to retrieve information i might later need in the controller. For example,
Functions.getGrades()
.then(function(response)
{
$scope.grades = response.data;
});
Subjects.offered()
.then(function(response)
{
$scope.subjects = response.data;
});
Later on i pass these variables (grades or subjects) to a service where they are used for processing. However, these functions are randomly returning code 500 server errors after they run, and sometimes returning status code 0 after running. This happens in a random way and it is hard for me to point out the circumstances leading to their popping up. This leaves me with frequent empty Laravel-ised error screens like the ones shown below.
Anyone reading my mind?
Ok, after a suggestion given in a comment above that I check my Laravel log files (located in storage/logs/laravel.log- Laravel 5.1), i found out that the main error most of these times was this one: 'PDOException' with message 'SQLSTATE[HY000] [1044] Access denied for user ''#'localhost' to database 'forge'' in ..., plus another one that paraphrased something like No valid encrypter found. These were the key opener.
On reading another SO thread here, it said in part:
I solved, sometimes laravel not read APP_KEY in .ENV. And returns a value "SomeRandomString" (default is defined in config / app.php), and have the error "key length is invalid", so the solution is to copy the value of APP_KEY, to the value 'key 'in config / app.php, that's all! I solved!
That was exactly the issue! When loading the DB params from the .env to config/database.php, Laravel was sometimes unable to read the environment variables and went for the fallback default fallback options (forge for DB name and username and SomeRandomString for the APP_KEY). So, to solve this i just did as advised: copied the APP_KEY in .env to the config/app.php and edited the default DB parameters to the actual DB name and username/password I'm using. Just that and i was free from pollution. Hope someone finds this helpful.

Sending a '$param' in a post request

I am currently writing an angular, express, mongoose(monogodb) app and there is this strange behavior I am running into.
I want to send a mongoose query to the server side so in the client side I write the query as so
var query = {
'_id' : {'$in' : ['1958929ef']}
};
This gets passed into express.js however, when I console.log it the '$in' param is not there.
I get...
var query = {
'_id' : {}
}
When I change '$in' to just 'in' i can see there is no problem.
Why does this happen? Is it because of sanitize? (i removed the sanitize module from angular and the issue still occurs)

SignalR server doesn't consistently call methods on client

I have an AngularJS application that I intend to have receive communications via SignalR from the server, most notably when data changes and I want the client to refresh itself.
The following is my hub logic:
[HubName("update")]
public class SignalRHub : Hub
{
public static void SendDataChangedMessage(string changeType)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();
context.Clients.All.ReceiveDataChangedMessage(changeType);
}
}
I use the following within my API after the data operation has successfully occurred to send the message to the clients:
SignalRHub.SendDataChangedMessage("newdata");
Within my AngularJS application, I create a service for SignalR with the following javascript that's referenced in the HTML page:
angular.module('MyApp').value('signalr', $.connection.update);
Within the root for the AngularJS module, I set this up with the following so that it starts and I can see the debug output:
$(function () {
$.connection.hub.logging = true;
$.connection.hub.start();
});
$.connection.hub.error(function(err) {
console.log('An error occurred: ' + err);
});
Then I've got my controller. It's got all sorts of wonderful things in it, but I'll show the basics as relate to this issue:
angular.module('MyApp').controller('MyController', function($scope, signalr) {
signalr.client.ReceiveDataChangedMessage = function dataReceived(changeType) {
console.log('DataChangedUpdate: ' + changeType);
};
});
Unfortunately, when I set a breakpoint in the javascript, this never executes though the rest of the program works fine (including performing the operation in the API).
Some additional (hopefully) helpful information:
If I set a breakpoint in the SignalRHub class, the method is successfully called as expected and throws no exceptions.
If I look at Fiddler, I can see the polling operations but never see any sign of the call being sent to the client.
The Chrome console shows that the AngularJS client negotiates the websocket endpoint, it opens it, initiates the start request, transitions to the connected state, and monitors the keep alive with a warning and connection lost timeout. There's no indication that the client ever disconnects from the server.
I reference the proxy script available at http://localhost:port/signalr/hubs in my HTML file so I disregard the first error I receive stating that no hubs have been subscribed to. Partly because the very next message in the console is the negotiation with the server and if I later use '$.connection.hub' in the console, I'll see the populated object.
I appreciate any help you can provide. Thanks!
It's not easy to reproduce it here, but it's likely that the controller function is invoked after the start of the connection. You can verify with a couple of breakpoints on the first line of the controller and on the start call. If I'm right, that's why you are not called back, because the callback on the client member must be defined before starting the connection. Try restructuring your code a bit in order to ensure the right order.

Backbone js collection.create() how to only update view when server side save succeeds

I've looked for ages for this and have seen lots of similar posts and answers, but nothing that's exactly what I'm after. I may be approaching this the wrong way.
I'm trying to add a new model to a collection, but I want to do server side validation. If the server validation fails, I don't want the new model to be added in the (collection's) view.
NB. the situation is when I get a 200 success response code (my backend is cakephp, and cakephp receives the request and processes fine), but server validation means no save to database (i.e., I don't want to add to database because it would create an unwanted duplicate).
Here's my backbone code :
//
// Add the selected school as a school the user manages.
addTeacherSchool: function(view) {
attribs = view.model.attributes;
attribs.school_id = attribs.id;
delete attribs.id;
attribs.user_id = this.model.id;
this.teacherSchoolListView.collection.create(
attribs, {wait: true, success: this.addTeacherSchoolSuccess}
);
},
addTeacherSchoolSuccess: function(model, resp, options) {
// resp is false
},
In my backbone SchoolListView (this.teacherSchoolListView is an instance of SchoolListView) I have the code (in initialize:) :
this.listenTo(this.collection, 'add', this.render);
On the server side (cakephp), I return false if I already have a 'copy' of the model :
return new CakeResponse(array('body' => json_encode($error_count == 0)));
As you can see, I'm using wait: true in my collection.create() call. What that is doing atm is waiting until the response is back from the server before adding the 'item' to the view. BUT I don't want the item added if server side validation returns an error.
Also, addTeacherSchoolSuccess() is called (which should be happening because there is no error in the req. / resp. cycle, just in the server side validation.
Any ideas on how to achieve what I'm after?
NB. I can (and do actually - though I've removed it so my code snippets are simpler) do validation client side, but I also want my server side validation to function.

Resources