In Ajax->submit how to find the submission was success - cakephp

I have a view that contains a hidden <div>. I show the hidden <div>, and when I click on submit in the hidden <div>, I want to know the whether the result is a success or failure.
In case of failure the <div> must not hide. Right now, it is always hidden.

Sample code:
var element = document.getElementById(element_id);
element.innerHTML = '<p><em>Loading ...</em></p>';
xmlhttp.open("GET", fragment_url);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
element.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
xmlhttp.readyState change when your Ajax request is processed and the server responds.
xmlhttp.status gives you the return code from the server
xmlhttp.responseText gives you the response from the server - you can use this to ascertain whether your business logic is a success or a failure (send some error msg and check for it here)

#Cherian & #Pradeep failed to mention that you should intercept the onsubmit handler for your form. This handler should do the AJAX style form submission and prevent the default submission by returning 'false'.
<form action="submissionurl" method="post" onsubmit="formHandler(); return false;">
...
</form>
I'd also recommend the use of jquery, as it simplifies your code by a huge amountsubmit

Related

How to view the ParsleyJS errors without blocking form submition

Is there a way to get the list of errors from parsley.js? I have a form that has one field that I want validate and give feedback to the user as a warning, but I don't want the error state for that field to block form submission. I am handling the form submission myself, so I'm looking for something like
$("form[name='client']").on('submit'), function(e) {
e.preventDefault();
var form = $(this);
form.parsley().validate();
// pseudo code as I don't know how to do this yet with parsley
var errors = form.parsley().errors().filter(function(err) { return err.field != field_to_ignore })
if (errors.length ) {
// error handling
} else {
// submit form
}
});
You could change the inputs or excluded options when you click on submit so that your inputs are all excluded.
My Solution is to work with two validations:
1.The first one is binding the error to the UI.
2.The second one is after adding the data-parsley-excluded=true attribute to your field_to_be_ignore.
$("#myForm").on('submit'), function(e) {
e.preventDefault();
var form = $(this);
//the first validation bind the error message to the screen
if (form.parsley().validate() == false) {
$('myFieldToIgnore').attr('data-parsley-excluded','true');
//Now let make a second validation:
form.parsley().validate();
}
else {
//submit
}
});

implementation of custom validation on click of Save & Submit Button in angularjs

I am new to angularjs and I need to develop single page application. I have a requirement of implementation of angular validation.
I have 10 fields(input, select and listbox) on page and 2 buttons(Save and Submit). When i click on save then 6 fields(just for example) should have valid values and when i click on Submit button- 8 fields should be checked.
But problem is. if i used form tag on page then how to implement these validation.
Your help will be appreciated.
write this code in a controller
obj.hasErrorWithsubmit = function (form, field, validation) {
if (validation) {
return ($scope.submitted && form[field].$error[validation]);
}
return (form[field].$dirty && form[field].$invalid) || ($scope.submitted && form[field].$invalid);
};
obj.hasErrorWithsave = function (form, field, validation) {
if (validation) {
return ($scope.save && form[field].$error[validation]);
}
return (form[field].$dirty && form[field].$invalid) || ($scope.submitted ``&& form[field].$invalid); };
Write this in html
ng-class="{'classname':obj.hasErrorWithsubmit(Formname,'fieldname','validationType')}">
i.e
ng-class="{'classname':obj.hasErrorWithsubmit(myform,'textfield1','required')}">
ng-class="{'classname':obj.hasErrorWithsave (myform,'textfield2','required')}">
classname is a css class which makes the border red
By clicking on submit button make $scope.submitted =true
By clicking on save button make $scope.save =true

How to make parsleyjs only trigger validation on blur (for a field that has already failed validation)

I'm trying to figure out how to make parsleyjs only trigger validation on blur for a field that has already failed validation.
See http://jsfiddle.net/billyroebuck/zbmv2d3w/
Markup:
<form id="myform">
<label for="email">Email</label>
<input type="email" name="email"
data-parsley-required="true"
data-parsley-type="email"
data-parsley-custom
data-parsley-trigger="blur"
/>
<input type="submit" />
</form>
JavaScript:
window.Parsley.addValidator('custom',
function (value, requirement) {
console.log('custom validation triggered');
sleepFor(3000); // simulate a delay (testing only)
if (value == 'test#test.com') {
console.log('custom validation failed');
return false;
}
console.log('custom validation passed');
return true;
}, 32)
.addMessage('en', 'custom', 'custom validation failed');
$('#myform').parsley();
function sleepFor(sleepDuration) {
console.log('pretend this takes a while...');
var now = new Date().getTime();
while (new Date().getTime() < now + sleepDuration) { /* do nothing */
}
}
parsleyjs Version 2.2.0-rc1
The email field has validation rules to check:
a value is provided,
the value entered is a valid email address,
some custom rule (pretend this is an AJAX request)
I have the parsley-trigger attribute for this field set to blur.
Steps:
Open the console
Enter "a#b.com" in the email field above and press tab
Note the custom validation is triggered (good)
Enter "xyz" in the email field and press tab
Note the parsley type validation kicks in (good)
Enter "xyz#test.com" in the email field View the console
Note the custom validation is triggered the moment the input becomes a
valid email (in this case when you press the letter c in .com) vs
blur :(
How can I make sure the validation is only triggered on the blur event for invalid fields?
Thanks in advance!
I'm afraid there is no such option currently. The idea is to remove the error message as soon as possible and everyone appears to like this.

How do you show validation errors returned from WebAPI?

I am using latest version of angular.js and WebAPI & bootstrap.
Imagine a form with few textboxes & submit button. Once a user submits the form, data is validated by WebAPI call on server as we cant trust client side validations.
In API controller, we do all our business validations.
Assuming that data entered in all the textboxes are invalid:
How should i return error message from my WebAPI so that the form displays it properly ?
In normal MVC way without angular, this is easy. We can add errors to ModelState and the view will pick it and show the errors properly.
AngularJS has built in form validation:
WebApi
You can return errors in whatever format you want. I would recommend that the response should contain following information:
An error message describing the error
In which part of the request the error occured (Payload, url params, query params)
Which attribute triggered the error (email, password, ...)
The response should also have the correct error status code (400, 401, ...)
Client
Assume that your response looks like this:
{
"message": "Email is invalid",
"area": "payload",
"field": "email"
}
Create your form and make sure the name attribute is assigned, since in your form validation you will need the it. By now angular will append form validations states to your elements:
<input type="email" name="email" id="email" ng-model="user.email" ng-minlength="6" required />
You can now dynamically display error messages by accessing the validation fields:
<span ng-show="form.email.$error.required && form.email.$dirty">Email can not be empty</span>
The angular way is using form with the angular directive ng-valid. you can simply add it e.g. to your input:
<input type="text" ng-valid="myFunc()">
You can define myFunc() within your scope, do whatever you like and return a boolean value.
Now, just add ng-disabled to your submit button and bind it to angular's form $valid property:
<button type="submit" ng-disabled="!myForm.$valid">Cool Button</button>
Note: myForm is the name of your form.
Further information in the docs.
The solution for me was : https://stackoverflow.com/a/23087715/3290276
Just i needed to change two things 1)Get data and 2)low case the property modelState.
parseErrors(response.data)
function parseErrors(response) {
var errors = [];
for (var key in response.modelState) {
for (var i = 0; i < response.modelState[key].length; i++) {
errors.push(response.modelState[key][i]);
}
}
return errors;
}

Show Validation Summary in AngularJS on Form Submit

Is it possible to show a Validation Summary, a Div on top of the page with all the Validation error messages in angularjs , on form submit ?
I am coming from a .Net background and used to have a validation summary concept,all the examples i have seen in angular shows the error message right next to the control.
I am very new to angularjs , so an example or pointer to the right direction would be appreciated !
Thanks !
Yeah, you can use flags on each of your input fields, which will show a specific error message based on whether that flag is true or false.
For example:
<div ng-controller="signupCtrl">
<input type="text" id="username">
<input type="text" id="password">
<button ng-click="validate()">Sign-up</button>
</div>
Then, the validate function would run several other functions that would set flags. For example:
function signupCtrl($scope) {
$scope.validate = function() {
if( /* username is bad */ ) {
$scope.usernameError = true;
} else if ( /* password is bad */ ) {
$scope.passwordError = true;
} else {
// AJAX call to submit sign-up, or whatever
}
}
}
Your error messages would look like this:
<div class="error" ng-show="usernameError">Your username is bad</div>
<div class="error" ng-show="passwordError">Your password is bad</div>
Or, better yet, you can use a model, and only one error message:
<div class="error" ng-show="error">You {{field}} is bad</div>
But that second option would require some different tweaking of your code.

Resources