Jquery form validation before Ajax request - javascript

I have gone through other threads and used one for reference but still I am not able to find the solution.
My question is:
I am calling a function on button click now that function has validation after validation I am trying to post data with ajax request in submit handler, problem is my fields are getting verified but Ajax request is not invoked.
<input type="button" value="Register" id="registerP" onclick="registerPatient()" class="form-control input-sm btn-success ">
function registerPatient(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: "patientName=" + patientName,
success: function(response){},
error: function(e){}
});
}
});
}
However if I am not using validation and calling Ajax directly i am able to post the data. Please suggest where I am going Wrong.

You can try like this which call jquery form validation and check if validated:
$(document).ready(function(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
}
});
});
function registerPatient(){
var IsValid=$("#patientRegistration").valid();
if(IsValid){
var patientName=""; //value for patient name
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: {"patientName": patientName},
success: function(response){},
error: function(e){}
});
}
}

Change your data syntax of ajax to this.
data: {patientName:patientName},
Make sure you have a parameter on catching method of the same name "patientName" to invoke its post from page on post.
This should work.
Also check if you get a patientName paramater value in your post. To do so first check by "alert" and pass the patientName parameter. You will know what you are getting and why post is not happening.

Related

Stop jQuery Ajax Success from preventing form submit

I am using jQuery validate with remote to check if an email address exists. Don't ask me why but I need it to redirect to a new page IF a match is found in the database (false), otherwise they should be able to use the form normally.
This code works perfect EXCEPT: if it returns true (meaning it didn't redirect) the form submit button doesn't do anything. I don't see any attributes assigned like disabled, but the form submission is defintely prevented. If I don't type anything in the email input, it will let me click the button.
rules: {
fullname: "required",
email: {
required: true,
email: true,
remote: {
url: "validate-email.php",
type: "post",
success: function(response) {
if(response === false){
window.location.href = 'new-page.html';
}
},
},
},
},
once I remove the success: section, form submission works normally so obviously it has something to do with what I did in there... Thank you in advance for your help!
Not sure if this is the best solution, but I was able to fix it by using this:
remote: {
url: "validate-email.php",
type: "post",
complete: function(data) {
if(data.responseText == "false"){
window.location.href = 'new-page.php';
}else{
return response;
}
},
Thank you for your help!

JQuery validator plugin passing data

I have a form with JQuery validator being applied to it. I wont post it all, but the code looks like the following
var validator = $("#my_form").validate({
errorPlacement: function(error, element) {
$( element )
.closest( "form" )
.find( "#error" )
.append( error );
},
rules: {
emailAddress: {
require_from_group: [1, '.datagroup'],
email: true,
maxlength: 40
},
mobileNumber: {
require_from_group: [1, '.datagroup'],
number:true,
minlength: 8
}
},
messages: {
emailAddress: {
maxlength: jQuery.validator.format("shorter")
},
mobileNumber: {
number: jQuery.validator.format("Please enter a number"),
minlength: jQuery.validator.format("Please enter a valid number")
}
},
groups: {
datagroup: "emailAddress mobileNumber"
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "php/main.php",
data: $(form).serialize()
})
.done(function (response) {
$('#results').html(response)
});
return false;
}
});
The problem is that the submit handler is passed the whole form, and then this data is serialized and sent to main.php. However,I no longer want the format it is submitting the mobileNumber in. The reason for this is that I am now using a plugin which will format this number for me, and to get the value of this, I need to do
var mobileNumber = $("#mobileNumber").intlTelInput("getNumber");
I can also grab the email using val() so this can be assigned to a variable as well. So how can I pass main.php the variables mobileNumber and emailAddress?
Thanks
You could do so, by manually constructing the data object like below.
$.ajax({
type: "POST",
url: "php/main.php",
data: {
'emailAddress': $("#mobileNumber").intlTelInput("getNumber"),
'mobileNumber': $("selector").val()
}
})

Validate and submit form with no page refresh

I'm using jQuery validation and processing the form via ajax so I can avoid a page refresh. The problem I am running into is that I can't figure out where to place the ajax code in the validation function so that the form won't send data until it's been validated.
For example:
$('#ticket_purchasing').validate({ // initialize the plugin
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
phone: {
required: true,
digits: true,
},
email: {
required: true,
email: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = "All fields in red must be filled*";
$("div.error-message span").html(message);
$("div.error-message").show();
} else {
$("div.error-message").hide();
}
},
submitHandler: function (form) { // for demo
// Do stuff here
}
});
$('form#ticket_purchasing').on('submit',function(e) {
//Send the serialized data to mailer.php.
$.ajax({
url:'ticket-purchase.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
// $('#sponsorship_request').slideUp();
// $('#ticket_purchasing').hide();
// $('.seats-form').fadeIn(1000);
},
error:function(data){
$("ticket_purchasing .error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
//$.post("mailer.php");
//Take our response, and replace whatever is in the "form2"
//div with it.
// $('#form2').show();
});
As you can see above I have both functions separated from each other, and because of this the form is submitting the data (which emails the information) even though it's not been validated yet. I tried using form.submit(); as show in the validator documentation, and putting the ajax code in there, but it was a no go with errors I couldn't solve.
Advice? I'm probably going at this all wrong haha.
Edit: Just added html for the form: https://gist.github.com/adrianrodriguez/26b6beee8bf5ba85a8ce
To be clear, the form works fine without the validation portion, meaning I can submit and collect the data without a page refresh without the use of the validation plugin.
Remove your $.ajax call as the actual form submission should happen after validation in the validate.submitHandler.
$('form#ticket_purchasing').validate({
//validation rules here
//invalid handler goes here
submitHandler: function(form) {
$.post('ticket-purchase.php', $('#ticket_purchasing').serialize(), successCallback());
}
});
BTW, changed your $.ajax to a $.post
Thanks for everyone's help. I eventually realized that I was going at it all wrong and found this answer:
submitHandler: function (form) { // for demo
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(data) {
console.log(data);
// Do stuff here
//$('#ticket_purchasing').hide();
//$('.seats-form').fadeIn(1000);
}
});
return false; // kill page refresh
}
Instead of going the traditional way of the ajax submit I just had to use the "form" parameter already provided from jquery.validation.js and then grab data from its attributes.
Thanks for everyones help!
$( "#target" ).submit(function( event ) {
});
between this.

How do I define the value of an input for a remote check of existing values (username)?

This is using jQuery 1.6.1 and Validate 1.8.1.
I have been banging my head against a wall because of this problem, and now I'm trying the other approach to try and solve this problem. I need to query the database for existing usernames so that someone signing up doesn't register the same one again.
HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
This time, I'm trying to use the remote function for the validate script:
$("#signup").validate( {
var username = $("#username").val();
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
},
},
submitHandler: function(form) {
form.submit();
}
});
The code in question that doesn't work is var username = = $("#uname").val();. Firebug gives the error missing : after property id.
I'm including the mentioned variable above inside validate() because I only want the value of the input after I've typed something into it, not upon loading of the page.
The other problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
What am I doing wrong?
As you can read How can I force jQuery Validate to check for duplicate username in database?
The solution is to use the remote property:
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
var username = $("#uname").val();
instead of
var username = = $("#uname").val();
You can't have = =, it's a syntax error.
Also, make sure you properly 'escape' $("#username").val().
If someone enters: myname&action=dosomethingelse I'd give it a fair change it will dosomethingelse.
New answer:
$("#signup").validate( {
var username = $("#username").val(); // -- this is wrong
rules: {
Username: {
required: true,
...
});
You can fix this the easy way by just not declaring the variable at all since you're only using it is one place, but that's no fun :D
The solution is a closure:
$("#signup").validate( (function () {
var username = $("#username").val();
return {
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
}
},
submitHandler: function(form) {
form.submit();
}
};
}()));
(I haven't tested it, there may be a typo or syntax error).
If you have no idea what this does or why, don't worry about it :D

Using jQuery validate to upload a form, using ajax in the submitHandler()... not working

I am using jquery validate with a form. I want to submit the form using ajax. When I put the ajax call in validate's submitHandler() The browser hangs. What's going on?
The error message I get when I enable the validate method's debug is:
uncaught exception: [Exception...
"Illegal operation on WrappedNative
prototype object" nsresult:
"0x8057000c
(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"
location: "JS frame ::
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
:: f :: line 132" data: no]
Which is too arcane for me to make sense of.
Some code:
$(document).ready(function() {
$("#loginForm").validate({
debug: true,
errorLabelContainer: $('div.error'),
wrapper: 'li',
rules: {
last_name: {
required: true
}
},
messages: {
last_name: {
required: "Please enter your last name."
}
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "test.php",
data: form,
success: function(msg){
console.log( "Data Saved: " + msg );
},
error: function(msg){
console.log( "Error: " + msg);
}
});
}
});
});
The form is a very vanilla form. Submitting via a standard POST works fine. Also, the validation works fine... it's just the submitting with ajax part that fails me.
You'll probably want to serialise that form before sending it - you probably don't want to send a DOM object
edit RE:comment - to select only some inputs and serialize -
$(form).find(":input[name=inp1] :input[name=inp2]").serialize()
call ajax method with php function
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
class Ajax{
public function submitForm($data=array()){
//form - name attribute
//do - ajax page do_
// get - ajax result
return '<script language="javascript" type="text/javascript">
$(document).ready(function (data){
$(\'form[name='.$data['form'].']\').validate({
submitHandler: function(form) {
$.ajax({
method : \'post\',
url : \'' . AJAX_PATH . ''. $data['do'].'\',
data : $(this).serialize(),
dataType : \'html\',
success : function(data){
$(\'form[name='.$data['form'].']\').slideUp(1000);
$(\''. $data['get'] .'\').html(data).fadeIn(1000);
//$(\''. $data['get'] .'\').html(data).fadeIn(1000);
},
error : function(data) {alert(\'missing file\'); }
});
return false;
}
});
});
</script>';
}
}
$ajax = new Ajax();
<?php echo $ajax->submitForm(array('do'=>'do_register.php','form'=>'register','get'=>'#message'));?>
Just to elaborate of tobyodavies answer. You might want to change your submission to
$.ajax({
type: "POST",
url: "test.php",
data: $(form).serialize(),
success: function(msg){
console.log( "Data Saved: " + msg );
},
error: function(msg){
console.log( "Error: " + msg);
}
});
The ajax function expects the data option to be a string (not entirely true but for this case it's fine) while your passing in the forms dom object.

Categories