Validate form with jquery-validate using ajax - javascript

I have the following problem, I have performed a function to update my data with PHP and Codeigniter, using AJAX too .. everything works fine, but it turns out that I want to validate my form using jquery-validate before performing the AJAX request, for that already I have my validation rules and my code is as follows:
function edit(id = null) {
if (!id) {
alert('error');
return;
}
$.ajax({
url: 'roles/get_data_id/' + id,
type: 'post',
dataType: 'json',
success: function(response) {
$("#edit_name").val(response.Name);
$("#edit_description").val(response.Description);
$("#form_edit").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success: function(response) {
if(response.success === true) {
$("#modal_edit").modal('hide');
alert('The data were updated');
$("#form_edit")[0].reset();
table_data.ajax.reload(null, false);
} else {
$("#modal_edit").modal('hide');
alert('Error updating data');
}
}// /succes
}); // /ajax
return false;
});
}
});
}
The code works fine .. update my data .. now my question is where to add the following code with my validation rules:
$('#form_edit').validate({
highlight: function (input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function (input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function (error, element) {
$(element).parents('.form-group').append(error);
}
});
This is my current code:
function edit(id = null) {
if (!id) {
alert('error');
return;
}
$.ajax({
url: 'roles/get_data_id/' + id,
type: 'post',
dataType: 'json',
success: function(response) {
$("#edit_name").val(response.Name);
$("#edit_description").val(response.Description);
$('#form_edit').validate({
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
},
submitHandler: function() {
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success === true) {
$("#modal_edit").modal('hide');
alert('The data were updated');
$("#form_edit")[0].reset();
table_data.ajax.reload(null, false);
} else {
$("#modal_edit").modal('hide');
alert('Error updating data');
}
} // /succes
}); // /ajax
return false;
}
});
}
});
}
this code my form:
<div class="modal fade" id="modal_edit" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="smallModalLabel">Edit rol</h4>
</div>
<form id="form_edit" action="<?php echo base_url();?>rol/edit" method="POST">
<div class="modal-body">
<div class="form-group form-float">
<label class="form-label">Name</label>
<div class="form-line">
<input type="text" id="edit_name" name="edit_name" class="form-control" maxlength="20" minlength="5" required>
</div>
</div>
<div class="form-group form-float">
<label class="form-label">Description</label>
<div class="form-line">
<textarea id="edit_description" name="edit_description" rows="3" class="form-control no-resize" required></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-link waves-effect">update</button>
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>

You can use the submitHandler provided by the jQuery validation, this way the AJAX will fire only when the validation rules are passed:
$('#form_edit').validate({
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
},
submitHandler: function() {
//your AJAX code goes here
edit(your_id_param_goes_here);
}
});

I have made you a WORKING DEMO,
I hope you will figure out how to continue from there.
HTML Changes:
<form id="form_edit">
<button id="submitForm" type="submit" class="btn btn-link waves-effect">update</button>
JavaScript:
$(document).ready(function() {
$("#submitForm").on("click", edit);
// introduce the validation rules to the form!
$('#form_edit')
.validate({
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
},
submitHandler: function(form) {
//Will execute only when the form passed validation.
OnSubmit(form);
}
});
function OnSubmit(form) {
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success === true) {
$("#modal_edit").modal('hide');
alert('The data were updated');
$("#form_edit")[0].reset();
table_data.ajax.reload(null, false);
} else {
$("#modal_edit").modal('hide');
alert('Error updating data');
}
} // /success
}); // /ajax
}
function edit(id = null) {
if (!id) {
alert('error');
return;
}
$.ajax({
url: 'roles/get_data_id/' + id,
type: 'post',
dataType: 'json',
success: function(response) {
$("#edit_name").val(response.Name);
$("#edit_description").val(response.Description);
return false;
}
});
}
});

Related

How can I serialize a form in JavaScript asp.net

I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.

laravel 5 validation ajax rendering error response in javascript to show error in view

i have a form validation to validate my adding data into database. I am a beginner in using ajax/javascript. How could i display error in my view using ajax.
I have already json return from ajax by this code:
if ($validator->fails()) {
return response()->json(['errors' => $validator->messages(), 'status' => 422], 200);
}
in my view i have this:
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 {{ $errors->has('catname') ? ' has-error' : '' }}" style="padding-bottom: 10px;">
<input class="form-control" name="catname" placeholder="Category name" type="text" required />
#if ($errors->has('catname'))
<span class="help-block">
<strong>{{ $errors->first('catname') }}</strong>
</span>
#endif
</div>
</div>
how can i return the errors to make my input type display the error .
Here is my ajax.
function addCategoryAjax(e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.addcat') }}",
type: "POST",
data: $("#frmAddcategory").serialize(),
dataType: "JSON",
success: function(data) {
if(data.status == 422) {
for (var error in data.errors) {
$('.errors').append(data.errors[error] + '<br>');
}
}
}
});
}
function addCategoryAjax(e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.addcat') }}",
type: "POST",
data: $("#frmAddcategory").serialize(),
dataType: "JSON",
success: function(data) {
//if success
console.log(data);
alert('success');
},
error: function(data){
//if error
if(data.responseJSON == 422) {
$('.errors').html('');
for (var error in data.responseJSON) {
$('.errors').append(data.responseJSON[error] + '<br>');
}
}
}
});
}

Bootstrap modal firing up incrementing times

Bootstrap Modal fires action one time and if I click again it will fire up twice and so on.
<div id="loginModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Log In</h4>
</div>
<div class="modal-body">
<h3>Username</h3>
<input type="text" id="userLogin" placeholder="Username">
<h3>Password</h3>
<input type="password" id="pwdLogin" placeholder="Password">
<br>
<br>
<input type="checkbox" id="rememberMe">Remember Me
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="btnLogin">Log In</button>
</div>
</div>
</div>
</div>
Here's the span that fires the modal.
<span id="comment"><a id="testComment" data-toggle="modal" href="#loginModal" class="btn btn-default">Add comment</a></span>
After I click the span the modal shows. I click the #btnLogin and then the action fires up one time, two times and so on.
javascript that interacts with the modal(the action is within the span click):
$("#testComment").click(function (event) {
if ($("#msg").val() == "" || $("#nombre").val() == "") {
alert("To send a comment fill your mail and message!");
event.stopPropagation();
}
else {
$("#btnLogin").click(function () {
alert("this also");
$(this).off('shown.bs.modal');
if ($("#userLogin").val() != "" && $("#pwdLogin").val() != "") {
var dataToSend = {
"action": "LOGIN"
, "username": $("#userLogin").val()
, "password": $("#pwdLogin").val()
, "remember": $("#rememberMe").is(":checked")
}
$.ajax({
url: "data/applicationLayer.php"
, type: "POST"
, data: dataToSend
, dataTpe: "json"
, success: function (jsonData) {
var data = {
"comment": $("#msg").val()
, "username": $("#username").val()
}
$.ajax({
url: "data/addComment.php"
, type: "POST"
, data: data
, dataType: "text"
, success: function (dataResponse) {
var newHTMLContent = "";
newHTMLContent += "<tr><td>" + data.username + "</td>" + "<td>" + data.comment + "</td></tr>";
$("#commentTable").append(newHTMLContent);
alert("Comment was added!");
}
, error: function (errorMsg) {
alert("Error adding comment in ajax");
}
});
}
, error: function (errorMsg) {
alert("Login Error");
}
});
}
else {
alert('Missing username or password.');
}
});
}
});
Just put $("#btnLogin").click event outside. Here is the my code or go with below link may be it can help you.
JSFiddle
JAVSCRIPT
$("#testComment").click(function(event) {
if ($("#msg").val() == "" || $("#nombre").val() == "") {
alert("To send a comment fill your mail and message!");
event.stopPropagation();
}
});
$("#btnLogin").click(function() {
alert("this also");
$(this).off('shown.bs.modal');
if ($("#userLogin").val() != "" && $("#pwdLogin").val() != "") {
var dataToSend = {
"action": "LOGIN",
"username": $("#userLogin").val(),
"password": $("#pwdLogin").val(),
"remember": $("#rememberMe").is(":checked")
}
$.ajax({
url: "data/applicationLayer.php",
type: "POST",
data: dataToSend,
dataTpe: "json",
success: function(jsonData) {
var data = {
"comment": $("#msg").val(),
"username": $("#username").val()
}
$.ajax({
url: "data/addComment.php",
type: "POST",
data: data,
dataType: "text",
success: function(dataResponse) {
var newHTMLContent = "";
newHTMLContent += "<tr><td>" + data.username + "</td>" + "<td>" + data.comment + "</td></tr>";
$("#commentTable").append(newHTMLContent);
alert("Comment was added!");
},
error: function(errorMsg) {
alert("Error adding comment in ajax");
}
});
},
error: function(errorMsg) {
alert("Login Error");
}
});
} else {
alert('Missing username or password.');
}
});

Clear jeasyui form fields after successful submit

I'm using a jeasyui form, inside a xoops module, in which I'm trying to clear all the form fields once the data has successfully submitted.
I've already consulted this question, but it didn't solve the problem in my case.
My HTML:
<div class="easyui-panel" title="Capture Reqs" style "width:100%;
max-width:600px; padding:30px 60px;">
<form action = "captureReqs_Save.php" id ="ff" class = "easyui-form"
method ="post" data-options = "novalidate:true">
<div style="margin-bottom:20px"> Area <br>
<input id="idArea" class="easyui-combobox" style="width:260px" name="idArea"
data-options="
url:'areasJson.php?idZona=<?php echo $idZone; ?>',
label:'Area:',
valueField: 'id',
textField: 'desc',
required:true
">
</div>
<div style="margin-bottom:20px"> Material
<input id="IdMaterial" class="easyui-combobox" style="width:100%"
name="IdMaterial" data-options="
loader: myloader,
mode: 'remote',
valueField: 'code',
textField: 'desc',
required:true
">
<div style="margin-bottom:20px"> Qty
<input class="easyui-textbox" name="quantity" style="width:100%"
data-options="label:'Qty:',required:true, validType:'number'">
</div>
<div style="margin-bottom:20px">
</form>
<div style="text-align:center;padding:5px 0">
<a href="javascript:void(0)" class="easyui-linkbutton"
onClick = "submitForm()" style="width:80px"> Submit</a>
<a href="javascript:void(0)" class="easyui-linkbutton"
onClick = "resetForm()" style = "width:80px"> Clear </a>
</div>
</div>
Script:
<script>
var myloader = function (param, success, error) {
var q = param.q || '';
if (q.length <= 2) {
return false
}
$.ajax({
url: 'materialJson.php?idArea=' + $('#idArea').combobox('getValue'),
dataType: 'json',
data: {
q: q
},
success: function (data) {
var items = $.map(data, function (item, index) {
return {
code: item.code,
desc: item.desc
};
});
success(items);
},
error: function () {
error.apply(this, arguments);
}
});
}
function submitForm() {
$('#ff').form('submit', {
onSubmit: function () {
return $(this).form('enableValidation').form('validate');
}
});
}
function resetForm() {
$('#ff')[0].reset();
}
</script>
Try calling resetForm. I converted to use promise style ajax and added resetForm
var myloader = function (param, success, error) {
var q = param.q || '';
if (q.length <= 2) {
return false
}
$.ajax({
url: 'materialJson.php?idArea=' + $('#idArea').combobox('getValue'),
dataType: 'json',
data: {
q: q
}
}).then(function (data) {
var items = $.map(data, function (item, index) {
return {
code: item.code,
desc: item.desc
};
});
success(items);
}).fail(function () {
error.apply(this, arguments);
});
}
function submitForm() {
$('#ff').submit(function () {
if ($(this).form('enableValidation').form('validate')) {
$.post($(this).attr('action'), $(this).serialize(), function (response) {
clearForm();
});
}
return false;
});
}
function resetForm() {
$('#ff')[0].reset();
}

Validation not firing submitHandler

As stated in the title, the submitHandler is not firing/being reached, but the validation is working correctly. The submit handler is in the correct, but not firing.
$(function () {
$("#form").validate({
rules: {
domain: {
required: true
},
playerClass: {
required: true,
}
},
submitHandler: function (form) {
var accountNumber = $("input#accountNumber").val();
var domain = $("input#domain").val();
var playerClass = $("input#playerClass").val();
var dataString = JSON.stringify([{
"accountNumber": accountNumber,
"playerClass": playerClass
}]);
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
$(".player-code").show();
},
failure: function () {
alert(dataString);
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
$(".player-code").show();
}
});
});
jsFiddle: Link
Because you don't have a real submit button. A div is not a button...
<div class="btn btn-default submit">Submit</div>
You need a button or input with type="submit" to trigger the submitHandler when the form is valid.
<input type="submit" class="submit" />
OR
<button type="submit" class="submit">Submit</button>
http://jsfiddle.net/e04rca0t/7/

Categories