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

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

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 do I reinitialise jquery validation after loading form through ajax

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

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

PHP / AJAX Post Security

On my website I have the following javascript/ajax code that is called when a user submits the logon form.
The login form then checks the information and passes back messages and PASS or ERROR.
On a success message I would then like the ajax to redirect to the php code again to double check for a valid logon before setting up the session, is this necessary? how would i "redirect" from within ajax whilst retaining the $_POST data?
//login form ajax
$("#login-form").submit(
function() {
$("#FormMessages").removeClass().addClass('alert alert-info').html(
'<img src="images/loading.gif" /> Validating....').fadeIn(500);
$.ajax({
url: $("#login-form").attr('action'),
dataType: 'json',
type: 'POST',
data: {
username : $('#email').val(),
password : $('#password').val()
},
success: function(data){
if (data.status == 'PASS') {
$("#FormMessages").fadeTo(
100,
0.1,
function()
{
$(this).html('Logging In...').removeClass().addClass(
'alert alert-success').fadeTo(450, 1,
function() {
document.location = curUrl;
});
});
} else {
$("#FormMessages").fadeTo(
200,
0.1,
function()
{
$(this).html('<h4>Error!</h4>')
.removeClass().addClass('alert alert-danger')
.fadeTo(450, 1);
$("#FormMessages").append('<ul>');
$(data.messages).each(function(i,obj) {
$("#FormMessages").append(''+obj+'');
});
$("#FormMessages").append('');
});
}
}
});
return false;
});
Thanks for reading!

jquery validation error while checking department name

I have used the jquery validation for checking the department name is already exist in the specific organization. But its not returning the correct result. Please someone help me.
Here is my Jquery:
$(document).ready(function(){
var validator = $("#frmAddDepartment").validate({
errorElement:'div',
rules: {
organization:{
required:true
},
department: {
required: true,
allowChars:true,
//remote:$('#site_url').val()+"admin/department/check_department/"+$('#department').val()+"/"+$('#Organization').val(),
checkdeptname:true
}
},
messages: {
organization:{
required:languageArray['select_organization']
},
department:{
required:languageArray['enter_department'],
//remote:jQuery.format(languageArray['dept_exist'])
}
}
});
jQuery.validator.addMethod("allowChars", function(value, element) {
var filter = new RegExp(/[^a-zA-Z0-9\-& ]/);
if(!(filter.test(value)))
{
return true;
}else
return false;
},languageArray['please_enter_valid_chars']);
jQuery.validator.addMethod("checkdeptname", function(value, element) {
returnResult = false;
$.ajax({
url: $('#site_url').val()+"admin/department/check_department",
type: "GET",
data:{department:value,organization:$('#Organization').val()},
success: function (result)
{
returnResult = result;
alert(returnResult);
}
});
//$.get( $('#site_url').val()+"admin/department/check_department", { department:value,organization:$('#Organization').val() }, function(data){alert(data);returnResult = result;} );
return returnResult;
},languageArray['dept_exist']);});
PHP controller's function:
public function check_department()
{
$sql_query=$this->department_model->check_department();
if($sql_query>0)
{
echo "false";
}else
{
echo "true";
}
}
I think , in your php controller function you are returning ture/flase as String and on ajax success call back function your are comparing it with boolean ture/flase.

Categories

Resources