how do i add validation to this method in angular controller? - javascript

Hi I have a controller where the post method still takes place even when an error comes up to say the fields weren't completed. You refresh the page and entry goes from the view.
$scope.create = function () {
var account = Account.save($scope.account);
modalService.success('Success! Your Account has been created!');
$uibModalInstance.close(account);
};
I have tried a few things, but they haven't worked. I need the method to return false if the form hasn't been filled in or fields are missing. Basically a 422 error; as the post goes to an api endpoint.
The example above is my code and need to add some validation into it, but just don't know where to start.
Really tired and need some help quickly.
Thank you in advance.

You could wait till that save method actually complete an ajax and then respond to you
var account = Account.save($scope.account).$promise.then(function(){
//success function
modalService.success('Success! Your Account has been created!');
$uibModalInstance.close(account);
}, function(error){ //error function
//here is the place you can do error handling part.
console.log('Error occured, do handle it here.')
});
Update
If you wanted to make sure before submitting form user should be enter a all form fields and all. Then you could take use of angular form validation feature. Where you can disabled form submit button till all form required fields are filled up & have required attribute over the fields which are required.

Related

Synchronous Requests Depreciated [duplicate]

I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

JS/JQuery/PHP - How to echo errors on form validate failure, and jump to div on success?

I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.

I need help finding an alternative to synchronous jQuery ajax

I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

MVC 3: running javascript after validation has completed but before the actual post?

Folks,
I have an MVC3 data entry form scenario that involves asking the user to confirm something after client-side validation has been satisfied, but before the post to the server.
Is there a way to insert some javascript into the sequence of events after the validation framework gives the go-ahead to post back, but before the post back happens?
(And of course if the user declines the confirmation, the post back has to cancel, too. )
Many thanks.
You could subscribe for the .submit event of the corresponding form and check if it is valid:
$(function() {
$('form').submit(function() {
if ($(this).valid()) {
// client validation passed successfully
} else {
alert('there was an error during client validation');
// cancel the submission of the form
return false;
}
});
});
or if you don't want to subscribe for the submission of the form and you want to verify if client validation passes for a given form you could always check like this:
var isValid = $('#someFormId').valid();

jQuery already submitted vs. being submitted

I'm working on a jQuery function that forwards form data to page without interfering with the normal submission. I can do it without any issues as long as I capture the submit using .submit(), but I would have to run my own validation on the data because it operates independently of the regular submission. Is there a way for jQuery (or any Javascript) to detect that form data has been posted and validated?
cheers,
Mike
Edit:
Workflow looks like this:
1. User enters data
2. Clicks submit
3. Site runs validation and accepts input
4. Submits data to new page
5. jQuery function detects new data was submitted and accepted so it runs.
More Edits for Clarity
I think you guys are missing the issue. I know how to detect a form is being submited (which is fine and dandy)
This is NOT what I want:
$(this).each(function(){
$(this).submit(function(){
*** Code ***
}
}
Suppose I have a validation script running independent of the code I am currently writing. How can I detect that this ran, and then go to the submit code above?
Use onsubmit="" on your <form> element, but return false. i.e.:
<form action="?" method="post" onsubmit="validate_and_submit(this);return false;">
The return false prevents the form from actually submitting so you can do stuff with AJAX.
Hope this helps!
What you need is AJAX here . So make a XHR request that goes to your server and posts data . The server's response would now go to a callback function ( your jquery function ) . If the data was validated and fine , you proceed further , else you stop .
What you are trying to do is not possible via the normal HTTP POST request .
EDIT: for the original clarification
If you want the server to only received validated data, then just make sure its not submitted to prior to the client-side validation occuring. You can do this with selectively calling event.preventDefault() based on the result of the validation.
$("#form").submit(function(event) {
//some stuff
if (validate(formdata) == false) {
event.preventDefault();
}
});
If you want a server to do the validation and submit to itself or another service, you should make that part of the server-side workflow. So it'd be like
1.) client submits to Service1
2.) Service1 validates
3.) Services1 submits to Service2 (such that service2 never receives code from elsewhere)

Categories