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.
Related
I am developing an app with the node, express, and mongoose. In my login module, res.render() the function sends the code back to the client side ajax call as string format data. Whereas I wanted it to render a particular view. ajax call is post type call. I can see the entire HTML in string format in success field of ajax.
I did search for similar problem and solutions, but I couldn't find any. Let me know what I am doing wrong.
Client Side :
$.ajax({
type: 'POST',
url: '/login',
data: userDetail,
success: function(data){
console.log(data);
},
error: function(err){
$("p").text("Invalid User Details")
}
});
Server Side :
app.post('/login', urlencodedParser ,function(req,res){
console.log(req.body);
User.find({name : req.body.name , password : req.body.pass},function(err,data){
if (data.length != 0){
Todo.find({},function(err,todo){
if (err) throw err;
var token = jwt.sign(req.body,config.secret,{
expiresIn : '1h'
});
res.render('todo',{
todos : todo,
token : token
});
});
}
else
res.status(401).json({ msg : "Invalid User" });
});
});
Ajax calls do not, by themselves, change what is displayed in the browser. They just fetch data and your Javascript code them decides what to do with that data. This is true no matter what type of Ajax call it is, GET, POST, etc...
If you want to change the current page to show the content you fetched with Ajax, then you have to insert that content into the current page yourself.
Or, in the case of a POST, perhaps you want to submit an HTML form and then the browser will render the content that comes back from that form post for you, but an ajax post will not change what the browser displays at all.
Submitting an HTML form can be done either via Javascript or via native user actions (without any Javascript). But, for the browser to process the result for you, it has to be the browser submitting the form, not an ajax call sending the form. If an Ajax call sends the form (as in the code you show), then the result just comes back to your Javascript and it's up to your Javascript to decide what to do with that result (insert it in the page, etc...).
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 on a remote server, consisting of just a text box and a submit button. Once this form is submitted (PHP) XML is returned. How can I go about using ajax/jQuery to fill out this form, submit it, and receive the XML to process?
Untested, I think you should be heading somewhere in the direction of the following JS. Ofcourse, this is light thinking, there could be all kind of implications with the following (eg. XSS protection etc..). But if we're talking a simple, plain form, I think this could work.
Also, expanding the following with some failure fallbacks etc would be good practice. For documentation on the Ajax function, check the API docs.
// This should be the URL where your <form> action's value is pointing at
var url = 'http://remote/form/action';
// The textfield's data you want to submit
var textFieldValue = 'foobar';
$.ajax(
url,
{
'type': 'POST', // Could also be GET, depending on your form
'data': {
'textFieldName': textFieldValue,
},
'success': function (data) {
console.log(data); // Your raw XML in a string
}
}
);
Edit: As Kevin B mentioned, you'll be heading into cross-domain policy problems with the above, making this situation that more complex. Therefor you should need to make sure you have CORS arranged on the targeted domain. See Wikipedia CORS for more info.
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);
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();