I basically copied an entire form submission code I had up and running on a Website and pasted it into a blank file in order to modify its contents and save some time. IN THEORY, then, if the original file stopped normal form submission from opening up the Action target file while still completing the submission, this one should do the same.
However, I can't get it to work like it did. I can't stop the submission from leaving the current window.
Can anyone please point me toward what I'm doing wrong?
(Aside from the PHP code I'm using the jQuery Validation Plugin, same as I was using in the previous form that worked as expected.)
Form HTML code:
<form id="form" class="appintro" method="post" action="manageform.php" enctype="multipart/form-data"></form>
JS
$.validator.setDefaults({
submitHandler: function() { //<-- Handler called by jQuery Validation once form is validated
$('.msg.sending').fadeIn(200);
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function() {
alert('Success')
},
error: function() {
alert('Failure')
}
});
return false; //<-- This should stop the normal submission...
}
});
I've also already tried calling the AJAX outside of the validator code, i.e. using $("form").submit(function(event)..., etc. Also tried setting data to form.serializeArray(), as recommended in some other SO post... Nothing does it.
Thanks in advance for your help!
EDIT 1
I've set up this jsFiddle to test it out in a simpler version. No matter what I place in AJAX's url, I get an error. If I fill the form's action, then I can't catch the submission.
Edit 2
Ok while fixing some bugs in my version of your js fiddle, I figured what the issue is.
This line is missing the form parameter
submitHandler: function() {
It should look like this:
submitHandler: function(form) {
Next, to call serialize, you need to wrap make it a jquery object. The form passed in by jquery validate is just a regular form object and not a jquery one. So you need to do this.
data: $(form).serialize(),
If you call form.serialize, you should get this error in Chrome: Uncaught TypeError: Object #<HTMLFormElement> has no method 'serialize', which could explain why your browser is reloading.
Edit 1
I looked at your fiddle and I found some bugs, but I'm not sure they fix your problem. I feel like I just fixed some errors specific to jsfiddle.
Here is a link to an updated fiddle that works: http://jsfiddle.net/JSuUL/6/
Here is the code with some annotations
$.validator.setDefaults({
// Need to pass in form variable
submitHandler: function (form) {
alert('Sending...')
$.ajax({
type: 'POST',
// First off changed this to make the request work
// http://doc.jsfiddle.net/use/echo.html
url: '/echo/html/',
// Instead of form, I used $(form) to reference the form as a jquery object.
data: $(form).serialize(),
success: function () {
alert('Success!')
},
error: function () {
alert('Failure!')
}
});
return false;
}
});
$(document).ready(function () {
// I added a "#" here so we can grab the form. Your jsfiddle had $(form)
$("#form").validate({
rules: {
name: {
required: true,
minlength: 2
},
surname: {
required: true,
minlength: 2
},
}
});
});
Related
My imported form will not validate using JQuery's $(form).validate() plugin.
I followed the example provided from this question and got the form working successfully. I moved my form to /html/external.html (I like to keep my main site in one file, index.php, and all my external forms/elements in a separate one), and calling the validation function did not work.
function validateForm() {
$('#registerForm').validate({
//rules
...
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: url,
data: $(form).serialize(), // Fixed typo
success: function () {
alert('succss')
}
})
return false;
}
})
}
$(document).ready(function() {
validateForm() // Validating the form on page load
})
$(document).on('click', '.toFormScreen', function() {
$('#welcome').remove() // Yes, #welcome was imported as well if the user was not logged in
$('#mainContainer').load('./html/external.html #registerForm')
validateForm();
})
The above does not work, because it cannot find the form element, being in a different file that's not imported on page load.
I tried adding the validation function below the load:
validateForm()
and that still doesn't work.
Is it possible to $(e).validate({...}) a form that has been imported/appended by a user at any given time after the page loads from an external HTML file?
EDIT: https://jqueryvalidation.org/ is the plugin I'm using.
The issue is because load() is asynchronous. Therefore you're instantiating validate() on #registerForm before it has been created in the DOM.
To fix this you need to place the call to validateForm within the callback of load():
$(document).on('click', '.toFormScreen', function() {
$('#welcome').remove()
$('#mainContainer').load('./html/external.html #registerForm', function() {
validateForm();
});
})
I have a standard silverstripe form that uses jquery validate to validate the required field. I need to perform some other validation prior to the form being submitted so have used the submithandler of jquery validate to perform an ajax request and if a successful result comes back, to submit the form as per the code below:
$('form').validate({
rules: {
{**MY FIELD RULES**}
},
submitHandler: function(form) {
$.ajax({
url: {**MY URL**},
success: function(response) {
var resp = JSON.parse(response);
if(resp.ErrorMessage == '') {
form.submit();
} else {
alert(resp.ErrorMessage);
}
},
});
}
});
When submitting the form using the code above, the Ajax function is called and returns correctly, however, when the form is submitted, I receive the following message:
ERROR [UNKNOWN TYPE, ERRNO 404]:
IN POST {MY FORM URL}
Line in
Trace
=====
SilverStripe\Dev\CliDebugView->renderTrace()
DetailedErrorFormatter.php:119
SilverStripe\Logging\DetailedErrorFormatter->output(404, , , , )
DetailedErrorFormatter.php:54
SilverStripe\Logging\DetailedErrorFormatter->format(Array)
HTTPResponse.php:355
SilverStripe\Control\HTTPResponse->outputBody()
HTTPResponse.php:283
SilverStripe\Control\HTTPResponse->output()
index.php:26
However, if I place the form submit before the ajax call like so:
$('form').validate({
rules: {
{**MY FIELD RULES**}
},
submitHandler: function(form) {
form.submit();
$.ajax({
url: {**MY URL**},
success: function(response) {
var resp = JSON.parse(response);
if(resp.ErrorMessage == '') {
// form.submit();
} else {
alert(resp.ErrorMessage);
}
},
});
}
});
The form submission works correctly.
I do have custom routing in this project, but I don’t think this is what is causing the problem as the form submission works in the second example. However, the routing.yml is as follows:
---
Name: myproject
---
SilverStripe\Core\Manifest\ModuleManifest:
project: mysite
SilverStripe\SiteConfig\SiteConfig:
extensions:
- SalonVision\SalonVision\SiteConfigExtension
---
Name: modelascontrollerroutes2
Before:
- '#modelascontrollerroutes'
After:
- '#adminroutes'
- '#graphqlroutes'
---
SilverStripe\Control\Director:
rules:
'$Salon/$Location/$URLSegment//$Action/$ID/$OtherID': 'SalonVision\SalonVision\CModelAsController'
and I am using $form->setFormAction($location->baseLocationURL().$form->FormAction()); to add the correct $Salon/$Location to the action URL.
I have tried disabling the security token with $form->disableSecurityToken(); just incase that was causing the problem but not joy.
Furthermore:
As I understand it, when you submit a Silverstripe form, the original form method is called (the one that generates the form) and then the form action method is called.
If I display the form page in my browser and then add a php die statement at the end of the form method, then submit the form, the die message is shown. If I place the die message at the start of the form action method, the error above is shown.
This means that the problem must lie when silverstripe is trying to call the form action method. I don’t know how this works internally but any thoughts would be greatly appreciated.
Now before i ask the actual question this is a stupid rant. I swear I hate javascript and everything that is associated with it.
Now actual question.
I have a asp.net web form. I can send data to my web api controller via asp.net code and its working. I'm trying to now post the data via client side ajax using jquery, but I can't get a simple true or false if the form is valid or not. Its a bootstrap v3 form. Someone please help me get off this wild ride. I've searched countless questions but no its not working. Everything is working including post and return message, just this stupid little thing wont't
I just wish to know how to get the form validity status before i ajax. Simple.
Edit:
this button click event works.
$("#additional").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/api/data",
data: $('form.form-horizontal').serialize(),
success: function(msg){
swal(msg,"Success","success");
},
error: function(){
swal("failure");
}
});
});
Basically I want the above ajax to run ONLY when form is valid. I have 'required' tags on my form fields already.
Your Question is not clear, but if you mean there is some inputs that they shouldn't be null or empty and after valid theme call ajax you can do some thing like this:
<form class="form-horizontal"> <input type="text" required class="SubscribeText" name="email"> <input type="button" class="postmethod" value="Send"></form>
$(".postmethod").click(function() {
if ($(".SubscribeText").val().length>0) {
$.ajax({
type: "POST",
url: "/api/data",
data: $('form.form-horizontal').serialize(),
success: function(msg){
swal(msg,"Success","success");
},
error: function(){
swal("failure");
}
});
}
});
if you have some inputs, the best practice is use flag, for on click flag=true, which input fails the validation should change the flag to false then if flag is true call ajax method.
I have the following HTML structure:
<form method="POST">
Name : <input id="asgname" type="text"> <br>
Description : <input id="asgdescription" type="text"> <br>
Save
</form>
I want that on clicking the save button, the form values are sent to the server via AJAX call.
For that, I've attached the click event via following command
$("#asgsave").click(save_assignment);
save_assignment is also a javascript function defined as follow:
function save_assignment() {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: $('form').serialize(),
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
The above is not working. So I tried the following approach as well:
function save_assignment() {
var formvalues = {
name : $('#asgname').text(),
descripion : $('#asgdescription').text(),
};
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: {values : formvalues},
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
But this is also not working.
Can anyone please guide me as to why are the above methods not working and what is the correct way to do so ?
EDIT-1 :
By not working, I mean: in the first case ($('form').serialize() approach) the data is not being sent to the server. I checked it via chrome and firefox debugger that there was no post data sent corresponding to the form.
And in the second case, empty values are being sent. i.e. the post data sent to server is like following:
values[name]
values[description]
i.e. the above values are empty.
EDIT-2:
By logging on firephp, I have confirmed that the save_assignment PHP script is BEING EXECUTED. Thus ajax call is working fine but it is NOT passing the data correctly.
Try to use event.preventDefault() like,
$("#asgsave").on('click',function(e){
e.preventDefault();
save_assignment();
});
or use return false after ajax call like,
function save_assignment() {
//ajax code
return false;
}
you have to use callbacks in the success function, cause ajax is asynchronously
edit
have you already tried console.log('foo'); in your function? so you are able to test if the function is called ;)
edit 2
add the following line to your ajax options
dataType: "json"
You could just serialize your form values:
http://api.jquery.com/serialize/
However, looking over your code, I'll take a stab and guess that you are not getting and sending your values properly. Using jQuery, you grab a value from input like so:
$('#idofInput').val();
http://api.jquery.com/val/
You are doing: $('#asgname').text()
Format your data properly: data : { foo : 'bar', bar : 'foo' }
One last guess, make sure your CodeIgniter config has CSRF protection disabled, otherwise you would need to pass: $this->security->get_csrf_token_name() & $this->security->get_csrf_hash();
Why my form need two clicks to submit using jQuery Validate?
contact_form.validate({ ... });
Demo: http://goo.gl/7jQjqY
Please help! Thanks!
Calling
$(form).submit(function() {
//
});
inside your submitHandler is incorrect: you are just adding the supplied function as an event handler for the form, but not actually calling it. So the first time you press the button, you are only defining a new event handler. The second press works because now that handler has been defined.
To fix, just remove the
$(form).submit(function() {
and corresponding
});
lines, putting your submit code directly in the submitHandler instead.
submitHandler: function(form) {
var str = $(this).serialize();
$.ajax({
url: 'process.mail.jsp',
type : 'POST',
data: str,
//dataType : 'json',
success: function(result) {
// etc
}
});
}
Working example here – it's literally just yours with lines 37 and 57 commented out.