I have a mixed client-side/server-side validation using jQuery validation plugin. The validation happens on both submit and for some fields on change. The form is being submitted via AJAX. There is another validation going on the application just before updating the DB.
If the data changes are not stored to the database due to this validation failing I'm returning the result via JSON to the JS method handling the AJAX form submission.
Ideally I would raise an error with custom message passed from the backend to JS by something like
$.validator.showErrors(obj);
as discussed here
Unfortunately the validator.showErrors(...) method is not defined in that context:
$(document).ready(function() {
$('.form').each(function() {
$(this).submit(function(e) {
e.preventDefault();
if ($.submitForm()) {
(...)
$.post(url, $.param(context), function(data) {
if (!data.success) {
$.validator.showErrors(...);
//$("#basicdetails").validate();
}
}, "json");
}
(...)
You can also see that I've tried form revalidation which should also trigger appropriate error (although more of an hack that the real solution).
I would like to retain static client-side validation and after ajax submission to be able to raise any errors that might have occurred on the backend.
Thank you for any help you can provide.
Pawel
.validate() is for setting up validation, to trigger it you should use .valid() like this:
$("#basicdetails").valid();
Related
I have an HTML form. I am already doing a client side HTML.
<form id='myForm' onsubmit='return myFormValidation()'>
...
</form>
Now, in myFormValidation function, after making sure the client side is OK, before really submitting the form, I want to do also a server side form validation.
I am using JQuery. So,I changed my function to something like this:
function myFormValidation(){
//first, client side validation
...
//then, server side validation
$.post(url_of_server_side, $("#myform").serialize(), function(json) {
data = JSON.parse(json);
if(!data.ok)
{
$("#msg").text("some error");
}
else
{
$("#myForm").submit();//Oops!
}
});
return false;
}
But the "submit" function of form behaves like a recursive function and tries to validate the form again!
Should I disable the validation function before calling submit? Or, I guess, there is a better way for my problem (which is slightly or even totally different than this)?
If you need server side validation you should extend your "Save" enpoint to support correct response status codes and do not use separate "Validation" url. Use single url with different response types:
200 (Success) - data was saved successfully
400 (Bad request) - input data was incorrect. As response message you can include "validation result" message which you will display to user.
So your code can looks like
$.post(url_of_server_side, $("#myform").serialize())
.done(function() {
//show some success confirmation or redirect to main page
}).fail(function(xhr, status, error) {
$("#msg").text(error.message);
});
I would suggest, if all data is OK, the server-side script to perform the action that you want, e.g. saving to database. That way, you will not need a second post of the form in case everything is correct.
If something is wrong, then obviously, the checks must take place the second time as well.
Morning,
I am submitting a form from jquery like:
$('#form').submit();
which successfully submits the form onto the server. However, I would like to return JSON from the post so I can dynamically update a modal without any redirection.
Though I could change my submit into a AJAX request. (so the return contents from the method will enter the success callback in the AJAX code) I already have the controller method accept my ViewModel object from the post so I can do easy validation on the server e.g.
If ModelState.IsValid Then
also I have the objects accessible to me (other posts suggest to serialize the data but with 20+ properties being sent, this will take a lot of effort on the server)
Is there anyway I can keep this same logic and return JSON? or will a re-write be required?
Thanks
Get the form data from the form and make an AJAX call.
$('#form').submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(json) {
alert(json);
}, 'json');
return false; // important to have this
});
Return json_encode($data) from your PHP file
I have a form which sends data to a CRM. If I create a simple HTML form and send the data to the server it will refresh my webpage and show the text:
{"success":false,"error":{"message":"<whatever the error is>"}}
or
{"success":true,"result":"ok"}
After styling the form and integrating animations and validations and stuff everything still works perfectly. Now the data is sent by using http://jquery.malsup.com/form/#getting-started. The server receives it but the user has no idea whether it did or not.
Using this jQuery form plugin or some other plugin you might want me to use(or even code) please help me display text inside a div whether the operation was successful or not, depending on the server's response.
I have only tried to display the response using the examples provided here: http://jquery.malsup.com/form/#ajaxForm but I have failed until now.
Here I've put together a JSfiddle with some form fields and the jQuery form plugin I am using in order to send the data to the server: http://jsfiddle.net/n78p9/1/.
I hope someone will be able to show me what I did wrong or show me another way of doing this.
Thank you!
EDIT #Arun: so it looks like this:
submitHandler: function(form) {
$(form).ajaxSubmit({
target: '.optional',
resetForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('Thank you for your message! Our team will contact you in the shortest possible time.')
}
});
}
I am definitely on the right way, but there is a problem: the error alert actually shows when the response is successful. I do not understand why. I have intercepted the POST request through a local proxy and re-sent it through the server and the server sent back this:
{"success":true,"result":"ok"}
But the script considered it an error. That is why I have inserted that text into the error:alert field:D.
What might be the problem?
Try using the callbacks provided by the library
var options = {
target: '#response',
success: showResponse,
clearForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('some error')
}
};
$('#contact-form').ajaxForm(options);
Is there any method in jquery like $.post , $.ajax etc which works like a normal form submission. I know about .submit() but it requires a form element , can we send a normal request without a form element in jquery?
You can submit without a form using $.ajax(). Further, to make it behave like a normal form would, set the async property to false.
$.ajax({
url: "/controller/action",
data: {'foo':'bar'},
async: false
});
This will result in you being sent to:
"/controller/action?foo=bar"
window.location.href = '/controller/action?foo=bar';
You are not clear on what you want to achieve. From what I understand, I'd suppose you want to send a GET or POST (form-submit-like) request to the server and make it seem like a real one.
In that case you would:
Create a XMLHTTPRequest with appropriate parameters.
Make it synchronous.
With the response, overwrite the DOM.
Not entirely clear what you are after, however you can use jQuery's serialize (docs) to pass a collection of values from input not in a form or any other items. You would still need to post the data in some manner however.
What I want to do is make a POST request with arbitrary params, much like submitting a form. That is not merely doing the XHR. What I ideally want is to emulate a submit (like submiting a form, not POSTiing and then redirecting). I want to avoid the latency of $.post + window.top.location = blah
The most direct way would be to have a 'fake' form and insert a bunch of elements, then serialize and use jQuery.submit(), something like Is there a way using jQuery to submit a form without the elaborate field by field breakdown?
I wish there were a more elegant way.
My use case is that I am gathering a bunch of random fields through external API calls (from Facebook and other services) and want to submit ALL that info at once to user creation, as if the user filled out all this information and pressed 'submit'
Any suggestions? Thanks!
yes
you can use $.ajax (example)
or $.post and $.get ... example:
$.post(
"url_to_page",
/* string like this: "text=me%20man&mail=peace#man.com or an object": */
{text: "me man", mail: "peace#man.com"}
)
/* you can check if the request was submitted successfully */
.success(function(data) {
alert("Success!");
alert(data); //data on page
})
/* you can check if the request failed */
.error(function() {
alert("Error!");
});