I am using following function to validate and send data to the php server:
$(document).ready(function () {
$(function() {
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
register_username: "required",
register_password: "required",
register_email: {
required: true,
email: true
},
register_confirm_password: {
required: true,
equalTo: '#register_password'
},
},
// Specify the validation error messages
messages: {
register_username: "Please enter your username",
register_password: "Please enter your password",
register_confirm_password: {
required: "Please provide a password",
equalTo:"Please enter password same as above."
},
register_email: "Please enter a valid email address",
},
submitHandler: function(form) {
var pdata = $(this).serialize();
alert(pdata);
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(this).serialize(),
dataType : 'json',
success: function(data) {
if (data.success){
console.log("Form is submitted.data is" + data.success);
$.each(data, function() {
$.each(this, function(k, v) {
console.log("key; " + k);
console.log("value; " + v);
});
});
}
else
{
console.log("The data returned is:" + data.success);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return false;
},
});
});
});
All the validation works, but the issue is with the line:
var pdata = $(this).serialize();
I am getting empty pdata:
alert(pdata);
I don't know why the data is not serialized here. Please help me to solve this.
Don't serialize $( this )
Try serializing the form instead.
$( "#register_form" ).serialize();
$(this) isn't what you think it is anymore. It's not #register_form, but instead the submitHandler function.
If you do console.log(pdata) you should see the function definition in your console.
The scope of the submitHandler function is not the form element, so this is not pointing to the element you require. It does however provide you with a parameter, which you've named form, that you can use instead, like this:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(form).serialize(),
// your code...
Related
I am loading a form via an ajax call. On the form I need to use jquery validation to validate the one text area.
The validation call is at the bottom of the page, but because the form isn't present when the page loads, I need to re-initalise it when the form has been loaded.
This is the code for the jquery validation:
class OpAuthSignIn {
static initValidationNotes() {
jQuery('.js-validation-notes').validate({
errorClass: 'invalid-feedback animated fadeInDown',
errorElement: 'div',
errorPlacement: (error, e) => {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: e => {
jQuery(e).closest('.form-group').removeClass('is-invalid').addClass('is-invalid');
},
success: e => {
jQuery(e).closest('.form-group').removeClass('is-invalid');
jQuery(e).remove();
},
rules: {
'notefield': {
required: true,
minlength: 1
}
},
messages: {
'notefield' : 'Enter some details for the note'
}
});
}
static init() {
this.initValidationNotes();
}
}
// Initialize when page loads
jQuery(() => { OpAuthSignIn.init(); });
Then this is my ajax call script. I have commented where I need to initilise the validation:
function openNotes(testID){
var dataString = 'pupilID=<?=$pupilID?>&testID='+testID+'&forename=<?=$forename?>';
console.log("datastring: "+dataString);
$.ajax({
type: "POST",
url: "note_sidebar.php",
data: dataString,
cache: false,
success: function(html) {
console.log("html returned: "+html);
if (html!="Error"){
document.getElementById("sidebarTitle").innerHTML = "Notes";
document.getElementById("sidebarContent").innerHTML = html;
//I need to now initialise the form
}else{
swal("Opps!", "There was an error loading the notes", "warning");
}
}
});
}
I would like to use a validate js plugin for a form (contact form with no refresh). I found this code below, where its author uses submitHandler key to send e-mails via AJAX and PHP. As the value there is a function function(form) { ... }. Could You tell me what is the purpose of the form parameter inside function(form)? The author doesn't even use it inside that function.
JS CODE:
$().ready(function() {
// validate the comment form when it is submitted.
$("#actualForm").validate({
focusInvalid: false,
onkeyup: true,
rules: {
// simple rule, converted to {required:true}
name: "required",
comment: "required",
email: {
required: true,
email: true
},
},
submitHandler: function(form) {
var name = $('input[name="name"]').val();
var email = $('input[name="email"]').val();
var comment = $('input[name="comment"]').val();
var params = {
"name": name,
"email": email,
"comment": comment,
};
console.log(data);debugger;
$.ajax({
url: 'email.php',
data: params,
type: 'POST',
dataType: json,
success: function (data) {
if (data.status) {
//Give success log to user
} else {
//Do something
}
}
});
}
I have problem with jquery validate plugn and history API, when i click few times
i have error jquery.min.js?_=1420288991396:4 Uncaught TypeError: undefined is not a function, when I comment a fragment with validate, script works fine. How concat this script.
In file script.js i have:
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
},
submitHandler: function() {
var username=$("#usernameLogin").val();
var password=$("#passwordLogin").val();
var dataString = 'username='+username+'&password='+password+'&tag=login';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
if($("#rememberMe:checked").val()){
checkCookie(username);
}
window.location.href = "index.php";
}
else{
$("#error").html("<label class='error'>Wrong password or username!</label>");
console.log("Wrong password or username!");
}
}
});
}
return false;
}
});
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
},
messages: {
firstname: {
required: "Please enter your firstname",
minlength: "Your firstname must consist of at least 3 characters"
},
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function() {
var username=$("#username").val();
var password=$("#password").val();
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
var dataString = 'username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&tag=register';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
console.log(data);
$(".register_notification").html("<label class='error' style='background:#6DC066'>Register successfully!</label>");
}
else{
$(".register_notification").html("<label class='error'>Username already exists, please choose another one!</label>");
}
}
});
}
return false;
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if (firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
$("footer a").click(function(e){
//e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl,success: function(data){
$('#login_box').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function() {
if(!location.pathname.localeCompare('/login.php')){
$.ajax({url:location.pathname,success: function(data){
$('body').html(data);
}});
}
else{
$.ajax({url:location.pathname,success: function(data){
$('#login_box').html(data);
}});
}
});
From jQuery library:
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
it shows throw e.
I can't think of any reason why using the browser's "back" button would cause the JavaScript to fail. Everything should be cached and continue to work as before.
The error you're getting is similar to the error you'd get if you failed to include the plugin.
Here is how you're including the jQuery Validate plugin...
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
Notice how you're hotlinking to the plugin hosted on the developer's own domain. (likely for his demos and/or to download.) This error might be caused by a timing issue, the plugin not loading fast enough from this URL.
The developer has provided his plugin on two different free CDN services where "hotlinking welcome". So instead of leaching the plugin directly from his domain, try hotlinking to the CDN links provided here.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
I am new to javascript and jquery and I'm trying to submit a form which is validated using the jquery validation plugin using the enter key. This is my code but the form is not being submitted as the alert isn't showing when you press enter. I'm not sure what exactly is happening. I think the page is simply being reloaded when i press enter. There's certainly no validation
<script>
$(document).ready(function() {
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid_' + element.attr('id'));
}
});
var validator = $("#login_form").validate({
rules: {
user_email: {
required: true,
email: true
},
password: {
required: true
}
},
messages:{
user_email:{
required:"Email required",
email: "Must be a valid email"
},
password: {
required: "Password required"
}
},
submitHandler: function(form) {
alert('submitted');
$.ajax({
type: "POST",
url: "ajax/check_login.php",
data: $(form).serialize(),
timeout: 3000,
success: function(resp) {
if (resp == 'error') {
$('#login_error').html('Invalid login');
} else {
load_user_area();
}
},
error: function(e) {alert('failed' + e);}
});
return false;
}
});
$(document).keydown(function(e) {
if (e.keyCode == 13) { $('#login_form').submit(); }
});
});
</script>
Thanks in advance for any help!
I have about 10 forms on one page with the same class. Each form should be able to validate and send individually. I am using the jquery validate plugin. I can't get it to work and all the forms are submitting the first one. Besides that I can't seem to target the errormessage div within a form with $(this).find('.error').html(error);
Each form looks like this:
<form method="post" class="alertform" action="">
<input type="text" onclick="clearText(this)" value="" class="required email" name="email">
<input type="hidden" value="1000004011320719" name="productid" class="productid">
<input type="submit" class="button" name="button" value="Set alert">
<div class="error"> </div>
</form>
My JS:
$('.alertform').each( function(){
$(this).validate({
rules: {
emailadres: {
required: true,
email: true
}
},
messages: {
emailadres: {
required: "Message 1",
minlength: "Message 2",
email: "Message 3"
}
},
errorPlacement: function(error, element) {
$(this).find('.error').html(error);
},
success: function(label) {
label.addClass("valid").text("")
},
submitHandler: function() {
var emailadres = $(this).find("input.email").val();
var productid = $(this).find("input.productid").val();
var dataString = 'emailadres=' + emailadres + '&productid=' + productid;
$.ajax({
type: "POST",
url: "/setalert.php",
data: dataString,
success: function(msg) {
if (msg==1) {
$(this).find(".email").attr("value", "");
$(this).find('.error').html("Pricealert set.")
}
else {
$(this).find('.error').html("Oops.")
}
}
});
}
})
});
Any help is appreciated!
I had a look at your HTML n JS, can you try this?
$('.alertform').each( function(){
var form = $(this);
form.validate({
Basically change all your $(this) into form through out ur code
This is common mistake about $(this), sometime it lost its reference.
Hope helps
:)
The complete working JS:
$('.alertform').each( function(){
var form = $(this);
form.validate({
rules: {
emailadres: {
required: true,
email: true
}
},
messages: {
emailadres: {
required: "Required",
minlength: "Fill it in",
email: "Not valid"
}
},
errorPlacement: function(error, element) {
element.nextAll('div').html(error);
},
success: function(label) {
label.addClass("valid").text("")
},
submitHandler: function() {
var email = form.find("input.email").val();
var productid = form.find("input.productid").val();
var dataString = 'email=' + email + '&productid=' + productid;
$.ajax({
type: "POST",
url: "/myurl.php",
data: dataString,
success: function(msg) {
if (msg==1) {
form.find(".email").attr("value", "");
form.find('.error').html("Thanks")
}
else {
form.find('.error').html("Something went wrong")
}
}
});
}
})
});