How do I reinitialise jquery validation after loading form through ajax - javascript

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");
}
}
});
}

Related

Jquery Autocomplete not populating after error thrown

I am running a ASP.Net MVC application and using jQuery's Autocomplete in one of the textboxes to populate contract numbers after the 6th digit/character.
It is working flawlessly, until after an error is thrown for a validation check.
My code :
$(document).ready(function () {
$("#ContractNumber").autocomplete({
source: '#Url.Action("GetContractId")',
open: function () { $('ul.ui-autocomplete').hide().fadeIn() },
close: function () { $('ul.ui-autocomplete').show().fadeOut() },
minLength:6
});
});
The code that redirects to the correct controller to get the contract number is here:
$(document).ready(function () {
//$('body').on('focus', "#ContractNumber", function () {
$("#ContractNumber").autocomplete({
source: function (request, response) {
$.ajax({
url: "/PurchaseRequestDetail/GetContractId",
minLength: 1,
data: { Prefix: request.term },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };;
}))
}
})
}
});
Here is the autocomplete that is working fine, before the error:
I wanted this autocomplete to work, on focus of the textbox, whether a validation error thrown or not.
validation error:
The code that checks for ModelState if contract number is not found :
if (contractNo is null)
{
// row.ContractId = foundList.ContractId;
db.PurchaseRequestDetail.Add(newRow);
db.SaveChanges();
}
else if (contractNo != null)
{
if (foundList is null)
{
ModelState.AddModelError("ContractNumber", "Contract Number not in the database.");
// reload the drop down lists, they don't survive the trip to the server and back
viewModel.ContractList = GetContractList(viewModel.ContractId);
return View("CreateEdit", viewModel);
}
}
Any pointers in correcting this would be helpful.
TIA.

How to send the validation response to PHP controller instead of Ajax

I'm using jQuery validator to test the phone field , but when i'm trying to send the form it's trying to execute ajax , I want it to run a function on the controller
$("#form-profile-information").validate({
rules: {
tel: {
minlength: 10,
maxlength: 10,
number:true,
phoneStartingWith6: true
},
},
messages: {
tel: "This is not a valid phone number",
}
});
if ($('#form-profile-information').valid()) {
$('#form-profile-information').submit();
}
I'm also using this function in another form using ajax
$.validator.setDefaults({submitHandler: function() {
$('#signup-form .alert-danger').addClass('hidden');
params = $('#signup-form').serializeArray();
ajax('post', params, function(data) {
if(data) {
$('#signup-form').slideUp();
$('#email-signup').text(data.emailValue);
return;
}
}, function(data){
$('#signup-form .alert-danger p').text(data);
});
}
});
When i use it I get Ajax.php executes and this error in the network : no-referrer-when-downgrade
Problem solved ,
I had to add a condition on the ID before the validator
if($("#form-profile-information").length>0) {
$.validator.setDefaults({submitHandler: function() {
$('#signup-form .alert-danger').addClass('hidden');
params = $('#signup-form').serializeArray();
ajax('post', params, function(data) {
if(data) {
$('#signup-form').slideUp();
$('#email-signup').text(data.emailValue);
return;
}
},
function(data){
$('#signup-form .alert-danger p').text(data);
});
}
});

If user manipulates the form id what is the best practice to secure it or stop this?

If user changes the formID what should i do to make the ajax call and jquery validation success.
<form id="formID" action="">
(function ($, W, D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function ()
{
$("#formID").validate({
rules: {
input:"required",
},
messages: {
input: "required",
},
submitHandler: function (form) {
var form = $('#formID')[0];
var formData = new FormData(form);
$.ajax({
type: 'post',
url: '/',
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.response == true) {
alert('true');
} else {
alert('false');
}
}, error: function (jqXHR, exception) {
console.log(jqXHR.status);
}
});
}
});
}
}
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
Just remove var form = $('#formID')[0]; in the submitHandler. The form element is already exposed as an argument
The plugin will have already initialized before an ID could be changed by user in console and probably before any userscript or browser extension also
Changing an ID does not affect events already attached to that element.
Beyond that you can't control what a user does in their browser and just need to make sure your back end is secure

unable to send data via this.serialize

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...

JQuery .show() after replacing html erases styling in MVC 4 application

I have an empty div:
<div id="reportBody"></div>
with simple css:
#reportBody {
height: 100%;
}
The reportBody div is in a hidden modal that is called on button click. Using jquery/ajax to call the controller to build an iframe string to an SSRS report.
$(document).ready(function () {
$('#dashboardReportForm').validate({ // initialize the plugin
rules: {
BrewerySelect: {
required: true
},
LineSelect: {
required: true
},
datepicker: {
required: true,
date: true
}
},
errorElement: "div",
errorPlacement: function (error, element) {
element.after(error);
},
submitHandler: function (form) {
var brewery = document.getElementById('BrewerySelect').value;
var line = document.getElementById('LineSelect').value;
var day = document.getElementById('datepicker').value;
var url = '#Url.Action("GetUrl")';
$.ajax({
url: url,
data: { breweryCode: brewery, packageLine: line, date: day },
dataType: 'json',
cache: false,
type: "POST",
success: function (data) {
var url = '<iframe src="' + data + '" height="100%" width="100%" scrolling="auto"></iframe>';
$('#reportBody').html(url).show();
},
error: function (response) {
alert('document.ready() dashboardReportForm.validate method failed');
}
});
ResetStyle();
$('#reportModal').modal('show');
}
});
});
It is the $('#reportBody').html(url).show(); in that code that replaces the inner html of the div. When I hardcode the iframe and skip this method it displays perfectly. When I use this method it breaks, the height: 100% does not show in chromes tools after inspecting at all.
How do I prevent this from happening or, failing that, reinsert it in the same method.
Thanks.
The answer: Hard code the style into the div.
<div id="reportBody" style="height: 100%;"></div>

Categories

Resources