How to update Parent form from a Modal - javascript

I have a modal form that updates a client's address once the "save" button is clicked. I want to use a AJAX call to update the Model's data once the modal form is closed. It would then redirect back to the parent form from which the modal form was called (Index.cshtml). The AJAX call is successfully retrieving the updated modal form's data via the textboxes but it always throws an error.
TL;DR: Want to close a modal form, redirect to parent form and update the text displayed there.
Please see below for my code snippets:
Controller
[ValidateInput(false), HttpPost]
public JsonResult UpdateClientDetails(Client newClientDetails)
{
_clientService.UpdateClient(newClientDetails);
return Json(newClientDetails);
}
$('.btn-update-client').click(function (e) {
var id = $(this).val();
$('#updateClientModal .modal-content').load('/client/UpdateClientDetails/' + id);
$('#updateClientModal').modal('show');
});
View (Index.cshtml)
<div class="panel-body">
<label>Client Id: <span id="ClientId">#id</span></label>
<address>
<span id="Address1">#client.Address1</span>, <span id="Address2">#client.Address2</span><br>
<span id="City">#client.City</span>, <span id="Province">#client.Province</span><br>
<span id="PostalCode">#client.PostalCode</span><br>
<abbr title="Phone">P:</abbr> <span id="PhoneNumber">#client.PhoneNumber</span>
</address>
<div><button value="#id" type="button" class="btn btn-primary btn-update-client">Change</button></div>
</div>
__
Controller Method
public ActionResult Index()
{
return View(_clientService.GetClientList());
}
Modal Form
#model Client
#using ProductManager.Models
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">#Model.Name - ID: #Model.Id</h4>
</div>
#{
var attributes = new Dictionary<string, object>();
attributes.Add("class", "form-horizontal");
}
#using (Html.BeginForm("UpdateClientDetails", "Client", FormMethod.Post, attributes))
{
<div class="modal-body">
<div class="form-group">
<label for="clientAddress1" class="col-xs-3 control-label">Address 1</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientAddress1" name="Address1" value="#Model.Address1">
</div>
</div>
<div class="form-group">
<label for="clientAddress2" class="col-xs-3 control-label">Address 2</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientAddress2" name="Address2" value="#Model.Address2">
</div>
</div>
<div class="form-group">
<label for="clientCity" class="col-xs-3 control-label">City</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientCity" name="City" value="#Model.City">
</div>
</div>
<div class="form-group">
<label for="clientProvince" class="col-xs-3 control-label">Province</label>
<div class="col-xs-9">
#Html.DropDownListFor(model => model.Province, (IEnumerable<SelectListItem>)ViewBag.ProvinceList, new { #class = "form-control", #id = "clientProvince" })
</div>
</div>
<div class="form-group">
<label for="clientPostalCode" class="col-xs-3 control-label">Postal Code</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientPostalCode" name="PostalCode" value="#Model.PostalCode">
</div>
</div>
<div class="form-group">
<label for="clientPhoneNumber" class="col-xs-3 control-label">Phone #</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientPhoneNumber" name="PhoneNumber" value="#Model.PhoneNumber">
</div>
</div>
<div>
<input type="hidden" id="clientName" name="Name" value="#Model.Name">
</div>
<div>
<input type="hidden" id="clientID" name="Id" value="#Model.Id">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
}
<script type="text/javascript">
$('.btn-primary').click(function () {
$.ajax({
type: 'POST',
data: getModelData(),
dataType: 'json',
success: function (data) {
$("#Address1").text(data.Address1);
$("#Address2").text(data.Address2);
$("#City").text(data.City);
$("#Province").text(data.Province);
$("#PostalCode").text(data.PostalCode);
$("#PhoneNumber").text(data.PhoneNumber);
},
error: function () {
alert("Error occured!");
}
});
function getModelData() {
var dataToSubmit = {
Address1: $("#clientAddress1").val(),
Address2: $("#clientAddress2").val(),
City: $("#clientCity").val(),
Province: $("#clientProvince").val(),
PostalCode: $("#clientPostalCode").val(),
PhoneNumber: $("#clientPhoneNumber").val()
};
return dataToSubmit;
}
});
</script>
After clicking the "Save" button on my modal form, it redirects to http://localhost:6969/Client/UpdateClientDetails/1234 with the following string:
{"Address1":"38 Lesmill Rd","Address2":"Suite 1",
"City":"Toronto","Province":"ON","PostalCode":"M3B 2T5",
"PhoneNumber":"(416) 445-4504","Id":2827,"Name":"Advisor Centric"}

If you are being redirected when you click the save function, it could be due to a few reasons. The below snippet should solve your problems.
$(document).on('click', '.btn-primary', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
data: getModelData(),
dataType: 'json',
success: function (data) {
$("#Address1").text(data.Address1);
$("#Address2").text(data.Address2);
$("#City").text(data.City);
$("#Province").text(data.Province);
$("#PostalCode").text(data.PostalCode);
$("#PhoneNumber").text(data.PhoneNumber);
},
error: function () {
alert("Error occurred!");
}
});
function getModelData() {
var dataToSubmit = {
Address1: $("#clientAddress1").val(),
Address2: $("#clientAddress2").val(),
City: $("#clientCity").val(),
Province: $("#clientProvince").val(),
PostalCode: $("#clientPostalCode").val(),
PhoneNumber: $("#clientPhoneNumber").val()
};
return dataToSubmit;
}
});
Changes to snippet explained:
Instead of using the jQuery click method, I have updated this to use the on method. This will allow us to attach an event to the btn-primary class even if it is loaded after the dom has been rendered.
We are now passing in the event object into the method. This allows us to prevent any default behavior that is expected, for example submitting the form traditionally. This is accomplished with the event.preventDefault() method.

Related

Using Modal JavaScript in the Partial View of .NET CORE will not work after Ajax Post

I use the Modal display field in the Partial View to input data for the User, and use data-url=#url.action("Create") in the main screen to call Modal.
And wrote Autocomplete JavaScript in Partial View.
It works perfectly before using Ajax Post.
But after going through Ajax, the JavaScript cannot be used when it returns because of an error.
How can I make corrections?
Main View
<div id="PlaceHolderHere" data-url="#Url.Action("Create")"></div>
Ajax Code
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
});
});
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
console.log(sendData);
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
console.log(redata);
if (redata.status === "success") {
PlaceHolderElement.find('.modal').modal('hide');
}
else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
}
},
error: function (message) {
alert(message);
}
})
})
})
Partial View of JavaScript part
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/bootstrap-autocomplete/dist/latest/bootstrap-autocomplete.min.js"></script>
$('#BossName').autoComplete({
resolver: 'custom',
minLength: 2,
formatResult: function (item) {
return {
value: item.value,
text: "[" + item.value + "] " + item.text,
}
},
noResultsText:'There is no matching data, please confirm whether there is data in the company field',
events: {
search: function (qry, callback) {
// let's do a custom ajax call
$.ajax(
'#Url.Action("GetRolesByAutoComplete","Roles")',
{
data: {
'q': qry,
'key': document.getElementById('CompanyCode').value
}
}
).done(function (res) {
callback(res)
});
}
}
});
$('#BossName').on('autocomplete.select', function (evt, item) {
console.log(item);
$('#BossID').val(item.value);
$('#BossName').val(item.text);
});
Partial View of Modal
<div class="modal fade" id="AddEditRoles" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AddEditRolesLabel">Add New Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" id="Edit">
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.RolesCode)</span>
#if (Model != null && Model.RolesCode != null)
{
<input asp-for="RolesCode" class="form-control" readonly />
}
else
{
<input asp-for="RolesCode" class="form-control" autocomplete="off" />
}
<span asp-validation-for="RolesCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.Title)</span>
<input asp-for="Title" class="form-control" autocomplete="off" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.CompanyCode)</span>
<input type="text" asp-for="CompanyCode" class="form-control col-md-3" readonly />
<input type="text" id="CompanyName" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="CompanyCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.BossID)</span>
<input asp-for="BossID" type="text" class="form-control col-md-3" readonly />
<input id="BossName" type="text" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="BossID" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<div class="text-danger">#Html.ValidationMessage("error")</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="Save" type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
You send data to the server, but when it fails you replace modal contents.
Replacing HTML destroys everything that was already there, so you wipe everything that was done by your autocomplete plugin.
All you need to do is to initialize autocomplete again:
success: function (redata) {
if (redata.status === "success") {
} else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
// INITIALIZE AUTOCOMPLETE HERE
}
},

How to submit form in jquery

This maybe a simple problem, but I can't find the cure.
When I executes this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit();
});
Everything works fine. But when I do this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit(function (e) {
var result = '#TempData["StatusMsg"]';
e.preventDefault();
if (result == 'Success') {
alert("Saved Successfully.");
}
})
});
This is my code behind :-
[HttpPost]
public ActionResult SaveQuotePreparation(QuotationPreparationEntity quoteP)
{
string result = objManager.SaveQuotePreparation(quoteP);
if (!string.IsNullOrEmpty(result) && (result == GeneralConstants.Inserted || result == GeneralConstants.Updated))
{
//Payment Gateway
data = GeneralConstants.SavedSuccess;
TempData["StatusMsg"] = "Success";
}
return new JsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My HTML is a long code , I've made it short just for understanding :-
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<form>
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo),
new
{
#class = "form-control requiredValidation",
#id = "QuoteNo",
#data_inneraction = "validationCall",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)"
})
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine),
new
{
#class = "form-control requiredValidation",
#id = "ProductLine",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)",
ng_model = "ProductLine",
ng_change = "GetProductLineDetails(ProductLine)"
})
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</form>
The Event don't fire on click. I don't get any error or anything.
I want to return JSON data on submit and show it as an alert on the screen.
You can do form submit in javascript like this..
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
successFunction()
}
},
error: function (xhr, desc, err) {
}
});
});
The From will define like this
<form class="form-horizontal" id="frm" name="frm" action="/Controler/Action" method="post" enctype="multipart/form-data"></form>
And Need to create the button as submit
<input type="submit"/>
i dont have your html code but ,
if you want your form to be submitted by on click event :
$('#save_results').on("click", function () {
e.preventDefault();
$('#formSaveQuotationPrepDetail').submit();
if (result == 'Success') {
alert("Saved Successfully.");
}
});
take a look at this example to see difference between your first and second code .
NOTE : in your code result is not defined , i am not sure where have you brought it from
You did mistake in view page. Please remove <form> tag inside view page. It will work.
You only use below code instead of your code:
note: Html.Beginform() method work as tag in HTML
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo), new { #class = "form-control requiredValidation", #id = "QuoteNo", #data_inneraction = "validationCall", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)" })
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine), new { #class = "form-control requiredValidation", #id = "ProductLine", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)", ng_model = "ProductLine", ng_change = "GetProductLineDetails(ProductLine)" })
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</div>
}

Form in ajax post method sends empty object

I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.

AngularJS 1.6.8: Form data not submitting and so hence unable to save it to localStorage

I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
There are no errors in console.

form submitting twice via ajax POST

Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<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"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;

Categories

Resources