form submitting twice via ajax POST - javascript

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;

Related

$(this).serialize() not working in jQuery validate submitHandler

I have a situation where i have the same form multiple times on a page in my application which allows users to edit or remove data however when using the below javascript to listen for the form submission the page just refreshes.
I was going to use $('.service_form').serialize() to submit the forms however when doing so it serializes values from every form on the page and completes the ajax request however if i use $(this).serialize() the page just refreshes.
HTML Form
<div id="service_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form class="service_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class='form-group has-feedback has-feedback-left'>
<label for="service_idno">IDNO:</label>
<input type="text" class="form-control required" id="service_idno" name="service_idno">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_code">Service Code:</label>
<input type="text" class="form-control required" id="service_code" name="service_code">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_cost">Service Cost:</label>
<input type="number" class="form-control required" id="service_cost" name="service_cost">
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Commit" class="btn btn-success" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
Javascript
$('.service_form').each(function(){
$(this).validate({
errorClass: 'validation-error-label',
highlight: function(element, errorClass) {$(element).removeClass(errorClass);},
errorPlacement: function(error, element){if (element.parents('div').hasClass('has-feedback')) {error.appendTo(element.parent() );}},
rules:{vali: "required"},
messages: {
service_idno: {required: "* Service IDNO Is Required."},
service_code: {required: "* Service Code Is Required."},
service_name: {required: "* Service Name Is Required."},
service_account: {required: "* Account Is Required."},
service_cost: {required: "* Cost Is Required."},
service_retail: {required: "* Retail Is Required."},
},
submitHandler: function(form) {
$.ajax({
url: "rest/servicedelete.php",
type: "POST",
data: $(this).serialize(),
timeout:9000,
beforeSend:function() {
$('.modal').modal('hide');
},
success: function (data) {
},
error:function() {
$('#notification').html('Remote Service Currently Unavailable');
},
});
}
});
});
I am wanting to be able to submit any form on the page at any time and only submit that data.
The scope of submitHandler() is not the form element, hence this is not what you expect it to be. Use the provided form parameter instead:
data: $(form).serialize(),
first you need to store current form in a temp variable like
$('.service_form').each(function(){
var form = $(this);
and then you do the serialize like
data: $(form).serialize(),
that will fix your issue.

Ajax success function not working on the second time

Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..

prevent form POST redirect from happening, but still keep bootstrap validation

So I have a form that I want to submit via AJAX. I use bootstrap, bootstrap material design, jquery and PHP codeigniter on the back-end.
Here is my problem: I want the html5/bootstrap validation to work, but I want the POST request to be sent via AJAX and not via redirect. Hence event.preventDefault() isn't an option... or so I think.
Any help is apreciated, thanks!
Here is my JS
$(document).ready(function(){
$.material.init();
$(".submit_form").click(function(event){
if ($('.reservation_form')[0].checkValidity()){
$('.app_loading').fadeIn('fast');
var input=$('.reservation_form :input');
var values = {};
var i=0;
console.log(input);
input.each(function() {
if (i==5){
values[i] = $(this).val();
}
else{
values[i] = $(this).val();
i++;
}
});
console.log(values);
jQuery.ajax({
type: "POST",
url: "https://code-igniter-blog-asergey91.c9users.io/index.php/reservation/make_reservation",
dataType: 'json',
data: {
email: values[0],
first_name: values[1],
last_name: values[2],
tel: values[3],
size: values[4],
start: values[5],
},
success: function(){
},
fail: function(){
$('.app_loading').fadeOut('fast');
$('.error_capacity').fadeIn('fast');
}
});
}
else{
$('.app_loading').fadeIn('fast');
$('.app_loading').fadeOut('fast');
}
});
});
Here is my HTML
<div class='container-fluid'>
<div class='row'>
<div class='col-xs-10 col-xs-offset-1 col-md-8 col-md-offset-2 col-lg-4 col-lg-offset-4'>
<div class='well customer_input'>
<form class="form-horizontal reservation_form">
<fieldset>
<legend class='text-center'>Make a Reservation</legend>
<div class='text-center'>Opening Hours:<br>Mon-Sat<br>8:00 AM - 8:00 PM</div>
<div class="form-group">
<label for="inputEmail" class="col-md-2 control-label">Email</label>
<div class="col-md-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<label for="inputFirstName" class="col-md-2 control-label">First Name</label>
<div class="col-md-10">
<input type="text" class="form-control" id="inputFirstName" placeholder="First Name" required>
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-md-2 control-label">Last Name</label>
<div class="col-md-10">
<input type="text" class="form-control" id="inputLastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label for="inputTel" class="col-md-2 control-label">Tel(+32)</label>
<div class="col-md-10">
<input type="tel" class="form-control" id="inputTel" placeholder="Telephone Number" required>
</div>
</div>
<div class="form-group">
<label for="inputParty" class="col-md-2 control-label">Party Size</label>
<div class="col-md-10">
<select id="inputParty" class="form-control" required>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputTime" class="col-md-2 control-label">Date+Time</label>
<div class="col-md-10">
<input type="datetime-local" class="form-control" id="inputTime" required>
</div>
</div>
<div class='app_loading text-center'>
<br>
<img src='../../assets/img/loading-dots.gif'>
</div>
<div class="form-group app_submit">
<div class='text-center'>
<button type="submit" class="btn btn-primary btn-raised submit_form">Submit</button>
</div>
</div>
</fieldset>
</form>
<div class="alert alert-dismissible alert-danger error_capacity">
<button type="button" class="close" data-dismiss="alert">×</button>
Sorry, this is an error message
</div>
</div>
</div>
</div>
<div class='row'>
<div class='col-xs-8 col-xs-offset-2 col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4'>
<div class='well customer_success'>
<h1 class='text-center'><span class='glyphicon glyphicon-ok'></span><br><br>Your Reservation Has Been Made<br><br>Thank You<br></h1>
</div>
</div>
</div>
</div>
Jquery Forms will be useful in this case. This will submit your form with Ajax without redirection.
Sample code:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind to the form's submit event
$('#myForm2').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];
alert('About to submit: \n\n' + queryString);
// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property
// if the ajaxSubmit method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property
// if the ajaxSubmit method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
Try to use
$( "form" ).submit(function( event ) {
event.preventDefault();
});
Remember you don't have to listen for click on any form submit button because any button in the form will submit it automatically as this is its default behavior
try adding
return false;
$(".submit_form").click(function(event){
if ($('.reservation_form')[0].checkValidity()){
$('.app_loading').fadeIn('fast');
var input=$('.reservation_form :input');
var values = {};
var i=0;
console.log(input);
input.each(function() {
if (i==5){
values[i] = $(this).val();
}
else{
values[i] = $(this).val();
i++;
}
});
console.log(values);
jQuery.ajax({
type: "POST",
url: "https://code-igniter-blog-asergey91.c9users.io/index.php/reservation/make_reservation",
dataType: 'json',
data: {
email: values[0],
first_name: values[1],
last_name: values[2],
tel: values[3],
size: values[4],
start: values[5],
},
success: function(){
},
fail: function(){
$('.app_loading').fadeOut('fast');
$('.error_capacity').fadeIn('fast');
}
});
}
else{
$('.app_loading').fadeIn('fast');
$('.app_loading').fadeOut('fast');
}
return false;

UPDATE form modal bootstrap in codeigniter using AJAX

Been struggling with this for about few hours. I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to choose a category of user. This is built in CodeIgniter. But when i try to save form's value using AJAX, the SUCCESS function won't run without alert(). I'm sorry for my bad grammar, i hope you can understand what i mean.
i need for your help...
view (kasir_halaman.php):
<div id="editModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Ubah Kasir</h3>
</div>
<div class="modal-body">
<form action="#" id="editform" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label> <span class="error" id="report1"></span>
<input type="text" id="editnama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="editemail" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" id="editkategori" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Simpan</button>
</form>
</div>
</div>
</div>
</div>
controller (kasir.php):
public function updatePetugas($id)
{
$nama_petugas = $this->input->post('nama');
$email_petugas = $this->input->post('email');
$kategori_petugas = $this->input->post('kategoripetugas');
$data = array('nama'=>$nama_petugas, 'email'=>$email_petugas, 'kategori'=>$kategori_petugas);
$update = $this->Crud->update(array('idpetugas'=>$id), 'petugas', $data);
if($update){
echo 1;
}else{
echo 2;
}
}
javascript (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/kasir/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
$(".edit").click(function(){
id = $(this).attr('id');
$.ajax({
url:'kasir/getData/'+id,
data:{send:true},
success:function(data){
$("#editnama").val(data['nama']);
$("#editemail").val(data['email']);
$("#editkategori").val(data['kategori']);
}
});
});
$("#editform").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'kasir/updatePetugas/'+id,
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
if(data==1){
$("#editModal").hide();
window.location.reload(true);
}else if(data==2){
alert('gagal');
}
}
});
alert("success!"); // if i remove this alert, the success function won't run or executed
});
});
you can solve this a few ways, what is actually happening is that you are submitting the data via ajax as well as submitting the form itself.
using e or the event
$("#editform").submit(function(e){
e.preventDefault();
or by returning false on submit
});
//alert("success!"); we can comment this out because it will work now without the alert holding the page
return false;
});
in either case you can remove your alert.

How to update Parent form from a Modal

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.

Categories

Resources