How to put Partial View inside Bootstrap Modal? - c#

I want to put a Partial View inside a Bootstrap Modal,
This is the JQuery code I'm using:
function CreateEmployeeModal()
{
var url = $("#btnCreateEmployeeModal").data("mine");
$.ajax({
type: 'get',
url: url
}).success(function (result) {
$(".modal-body").html(result)
$("#MyModal").modal('show')
}).error(function () {
alert("didn't work");
})
}
And this is the Modal code inside the _Layout file:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="divModalBody">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
I'm firing the modal using this button from the Index page, I've created the data-mine attribute to save the url to the Action Method that is returning the PartialView:
<input type="button" class="aslink modal-link" data-toggle="modal"
data-target="#myModal" id="btnCreateEmployeeModal" value="Open Modal" data-mine="#Url.Action("CreateUsingModal")">
This is the controller action method I have to return the Partial View:
public PartialViewResult CreateUsingModal()
{
return PartialView();
}
The operation is having success in ajax, but the modal doesn't show...

I had an error..., I should use a lowercase instead of a uppercase for the id of the modal... The correct way is: $("#myModal").modal('show')

I'll assume your GET endpoint (your method) is returning raw HTML.
A better way of doing this would be for your method to return your data in JSON format and then use that data to populate your modal window:
function CreateEmployeeModal()
{
var url = $("#btnCreateEmployeeModal").data("mine");
$.ajax({
type: 'get',
url: url
}).success(function (result) {
console.log(result); //better than alert
$("#textboxCorrespondingToValue").val(result.valueCorrespondingToTextbox);
$("#MyModal").modal('show');
}).error(function () {
alert("didn't work");
})
}
This way, if you even need to change the html you don't have to change anything in your server side code

Related

How to fix form submission error, form is using ASP.NET Core 3.1 and jQuery

I keep running into issues and I'm hoping the community can help me. I have a web application that was built a year or two ago using ASP.NET Core 3.1 with Razor Pages, and code behind (C#) files. The site is also using jQuery.
The form I'm having issues with is a "delete item" form. It's important that users confirm the item(s) they want to delete before they delete them from the database. On the front-end, we have DeleteItem.cshtml which is has the following code:
...
<form id="delete-form">
<label for="confirm-button">Step 1: Confirm</label>
<br />
<button id="confirm-button"
class="btn btn-primary"
data-toggle="modal"
data-target="#exampleModal">
Yes, I am sure I want to delete these questions.
</button>
<br />
<br />
<label for="submit-button">Step 2: Delete</label>
<br />
<div style="position:relative">
<div id="submit-div"
style="position: absolute; left: 0; top: 0; width: 25%; height: 100%; z-index: 1000;"></div>
<button id="submit-button" class="btn btn-primary" disabled="true">Delete</button>
</div>
</form>
</main>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Thank you for confirming you want to delete the question or questions listed. Please close this confirmation box, and select the delete button.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts {
<script>
$(document).ready(function () {
$('#delete-form').on('submit', function (e) {
e.preventDefault();
});
$('#confirm-button').click(function () {
$('#submit-button').prop('disabled', false);
});
$('#submit-div').click(function () { submitForm(); });
$('#submit-button').click(function () { submitForm(); });
function submitForm() {
console.log('in submitForm() function');
if ($('#submit-button').is(':disabled'))
alert('Please select the confirmation button before selecting the delete button.');
else
deleteButtonPush();
}
function deleteButtonPush() {
console.log('in deleteButtonPush() function');
if ($('#submit-button').is(':disabled')) {
alert('Please selete the confirmation button first.');
}
else {
$('#submit-button').prop('disabled', true);
$('#submit-button').append(' <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
$('#delete-form').prop('method', 'post');
$('#delete-form').prop('action', 'DeleteItem?id=#Model.Item.ItemTableID');
$('#delete-form').submit();
}
}
});
</script>
}
Why isn't the form being submitted, after clicking the confirmation button, and the delete button? I can see the delete button is disabled, and the spinner is added, after the submit-button button is clicked. However, the post isn't happening. How can this be fixed so post/submit will occur when the submit-button is clicked? Thanks, Everyone.
Remove the e.preventDefault() inside the on('submit') callback. Or if you want to check for other conditions, you can call the $('#delete-form').submit().
The problem with your code is after you calling the submit method on the form, then inside the submit callback, you cancel the default submit behaviors. For more information, you can read this Event.preventDefault()
// For example, you can read this code
$(document).ready(function() {
$('#delete-form').on('submit', function(e) {
// Checking condition
if (someError) {
// some error happen, don't submit the form
e.preventDefault();
// then if you want to submit the form inside this block, use this
// $("delete-form").submit();
}
// other things...
});
// ... Other things
})
Change your code like below:
<form id="delete-form">
<label for="confirm-button">Step 1: Confirm</label>
<br />
<!--Add type="button"-->
<button type="button" id="confirm-button"
class="btn btn-primary"
data-toggle="modal"
data-target="#exampleModal">
Yes, I am sure I want to delete these questions.
</button>
<br />
<br />
<label for="submit-button">Step 2: Delete</label>
<br />
<div style="position:relative">
<div id="submit-div"
style="position: absolute; left: 0; top: 0; width: 25%; height: 100%; z-index: 1000;"></div>
<!--Add type="button"-->
<button type="button" id="submit-button" class="btn btn-primary" disabled="true">Delete</button>
</div>
</form>
</main>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Thank you for confirming you want to delete the question or questions listed. Please close this confirmation box, and select the delete button.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts {
<script>
$(document).ready(function () {
//$('#delete-form').on('submit', function (e) {
// e.preventDefault();
//});
$('#confirm-button').click(function () {
$('#submit-button').prop('disabled', false);
});
$('#submit-div').click(function () { submitForm(); });
$('#submit-button').click(function () { submitForm(); });
function submitForm() {
console.log('in submitForm() function');
if ($('#submit-button').is(':disabled'))
alert('Please select the confirmation button before selecting the delete button.');
else
deleteButtonPush();
}
function deleteButtonPush() {
console.log('in deleteButtonPush() function');
if ($('#submit-button').is(':disabled')) {
alert('Please selete the confirmation button first.');
}
else {
$('#submit-button').prop('disabled', true);
$('#submit-button').append(' <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
$('#delete-form').prop('method', 'post');
$('#delete-form').prop('action', 'DeleteItem?id=#Model.Item.ItemTableID');
$('#delete-form').submit();
}
}
});
</script>
}
Everyone. Thank you for your feedback. With your help, the confirmation and delete buttons are working correctly now. I decided to use an AJAX request in order to solve the need to post/submit to the server. It's not finished yet, but here is an answer:
...
<form id="delete-form">
<h2>Questions to be Deleted</h2>
<p>Step 1: Select one or more questions</p>
#if (Model.Questions != null && Model.Questions.Count > 0)
{
<table class="table" summary="select one or more questions to be deleted">
#* output table of questions w/ checkboxes to select or "unselect" each question *#
</table>
}
<h2>Confirm and Delete</h2>
<p>
Please confirm you are sure you want to delete the question(s), reading passages, and/or science tabs,
for the question(s) listed above.
</p>
<input type="hidden" name="ID" value="#Model.Item.ItemTableID" />
<label for="confirm-button">Step 2: Confirm</label>
<br />
<button type="button"
id="confirm-button"
class="btn btn-primary"
data-toggle="modal"
data-target="#exampleModal">
Yes, I am sure I want to delete these questions.
</button>
<br />
<br />
<label for="submit-button">Step 3: Delete</label>
<br />
<div style="position:relative">
<div id="submit-div"
style="position: absolute; left: 0; top: 0; width: 25%; height: 100%; z-index: 1000;"></div>
<button type="button" id="submit-button" class="btn btn-primary" disabled>Delete</button>
</div>
#Html.AntiForgeryToken()
</form>
</main>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Thank you for confirming you want to delete the question or questions listed. Please close this confirmation box, and select the delete button.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts {
<script>
$(document).ready(function () {
$('#delete-form').on('submit', function (e) {
if ($('#submit-button').is(':disabled')) {
showDeleteError();
e.preventDefault();
}
else
deleteButtonPush();
});
$('#confirm-button').click(function (e) {
$('#submit-button').prop('disabled', false);
e.preventDefault();
});
$('#submit-div').click(function () { submitForm(); });
$('#submit-button').click(function () { submitForm(); });
function submitForm() {
console.log('in submitForm() function');
if ($('#submit-button').is(':disabled'))
showDeleteError();
else
deleteButtonPush();
}
function deleteButtonPush() {
console.log('in deleteButtonPush() function');
if ($('#submit-button').is(':disabled'))
showDeleteError();
else {
$('#submit-button').prop('disabled', true);
$('#submit-button').append(' <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
let data = $('#delete-form').serialize();
$.ajax({
type: "POST",
data: data,
url: "ProcessDeletetion?handler=Delete",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
console.log('ok')
},
error: function () {
console.log('error');
}
});
}
}
function showDeleteError() {
alert('Please select the confirmation button before selecting the delete button.');
}
});
</script>
}

Refresh PartialView in MVC Controller

I'm trying to refresh my Partial View after submitting a form which will be processed in my controller. The problem is that whenever I try to refresh it form my controller, I get redirected to a blank page with content from the Partial View.
Partial View
#model Smarty.Viewmodels.BugViewModel
<div class="modal fade" id="bugModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Bug Reporting Tool</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span>×</span>
</button>
</div>
<form asp-controller="Smarty" asp-action="SendBugReport" enctype="multipart/form-data">
#if (!string.IsNullOrWhiteSpace(ViewBag.message))
{
if (!ViewBag.IsError)
{
<span class="border border-success text-success">#ViewBag.message</span>
}
else
{
<span class="border border-danger text-danger">#ViewBag.message</span>
}
}
<div class="modal-body">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
<label asp-for="FormFile" class="control-label"></label><br />
<input asp-for="FormFile" type="file" />
<span asp-validation-for="FormFile" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
<button type="submit" id="BugReportBtn" class="btn btn-success">Bug Report senden</button>
</div>
</form>
</div>
</div>
</div>
Controller
public async Task<IActionResult> SendBugReport(BugViewModel viewModel)
{
//Process Form
return PartialView("BugModal", viewModel);
}
Thanks in advance!
I get redirected to a blank page with content from the Partial View.
That is expected because you use return PartialView() which will return the simple partial html to render it into the view.
I want to refresh the Partial View with content like Error Messages, Success messages etc
You could not get #ViewBag.message from the SendBugReport action, it is passed from the action of main page.
As the comment has said that, first of all, you could use ajax to submit the form to SendBugReport action.Then the action return message and isError json data to ajax success function. Finally, you render message on the view based on the value of isError:
1.Partial View (Views/Shared/BugModal.cshtml)
#model BugViewModel
<div class="modal fade" id="bugModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Bug Reporting Tool</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span>×</span>
</button>
</div>
<form id="myForm" asp-controller="Smarty" asp-action="SendBugReport" enctype="multipart/form-data">
<div id="result"></div>
<div class="modal-body">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
<label asp-for="FormFile" class="control-label"></label><br />
<input asp-for="FormFile" id="FormFile" name="FormFile" type="file" />
<span asp-validation-for="FormFile" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
<button type="button" id="BugReportBtn" class="btn btn-success">Bug Report senden</button>
</div>
</form>
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script>
$('#BugReportBtn').on('click', function (event) {
var url = "/Smarty/SendBugReport";
var description = document.getElementById("Description").value;
var fileInput = $('#FormFile')[0];
var formFile = fileInput.files[0];
var formData = new FormData();
formData.append("Description", description);
formData.append("FormFile", formFile);
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: "json",
processData:false,
contentType: false,
success: function (data) {
if (!data.isError) {
$("#result").html("<span class='border border-success text-success'>" + data.message + "</span>");
} else {
$("#result").html("<span class='border border-danger text-danger'>" + data.message + "</span>");
}
$('#bugModal').modal('show');
}
});
});
</script>
2.Action
[HttpPost]
public async Task<JsonResult> SendBugReport(BugViewModel viewModel)
{
//Process Form
string message;
bool isError;
//set data to message and isError
return Json(new { message, isError });
}

Not able to load partial view as modal when called from _Layout

In my Core 2.0 project I am trying to load a partial view to modal div when called from _Layout.cshtml but nothing happens. On click of Create New User I am trying to load partial view on modal popup. Below is code-
//_Layout.cshtml
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
<li>Create New User</li>
//Index.cshtml of Home
<div class="modal fade" id="AppointmentSchedule" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header btn-primary">
<h5 class="modal-title" id="AppointmentModalLabel"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="ScheduleAppointment"></div>
</div>
</div>
</div>
//Javascript
function CreateUser() {
var url = appSetting + "Home/CreateUser";
$.ajax({
type: "GET",
contentType: "application/json",
url: url,
data: null,
dataType: "html",
async: false,
success: function (data) {
$("#ScheduleAppointment").html('');
$("#ScheduleAppointment").html(data);
$("#AppointmentSchedule").modal('show');
},
error: function (result) {
$("#divScheduleAppointment").html('');
}
})
}
//Home Controller
public ActionResult CreateUser()
{
return PartialView("_CreateUserHome");
}
On debugging I realize that after Ajax success it calls Index action method of Home controller(that should not be) and may be it is causes page refresh and popup may get close. But what is it's solution.
With your current code, when user clicks on the anchor tag, the browser do a normal link click behavior, which is navigating to the href attribute value of the clicked link element. If you want show the modal dialog instead of that, you should prevent this default behavior.
You may pass an event object to the CreateUser method
Create New User
and in your method, call the preventDefault method, which will stop the normal link click behavior(navigating to to the href value)
function CreateUser(e)
{
e.preventDefault();
var url = appSetting + "Home/CreateUser";
$.ajax({
type: "GET",
url: url,
success: function (data)
{
$("#ScheduleAppointment").html(data);
$("#AppointmentSchedule").modal('show');
},
error: function (result)
{
$("#divScheduleAppointment").html('');
}
})
}
A suggestion: If it is not a navigational link, Consider using a button instead of an anchor tag.
Quick solution is to add return false to your event handler:
<li>Create New User</li>
This will suppress default behavior.

PartialView is returning fullpage, only rendering the form

I'm trying to rerender the partialview ONLY in my modal, after the ajax request.
But when I get the response everything is rerendered and the only thing showing is the partialview..
PartialView:
#{
var bidModel = new BidModel();
}
<div>
<div class="row">
#if (ViewBag.Message != null)
{
<div class="alert alert-success">#ViewBag.Message</div>
}
</div>
<span class=" alert-danger">
#Html.ValidationSummary()
</span>
<div class="form-group">
<input name="Bidder" asp-for="#bidModel.Bidder" value="#User.Identity.Name" type="hidden" />
<input name="AuctionId" asp-for="#bidModel.AuctionId" type="hidden" id="auctionId" />
<label asp-for="#bidModel.Amount" />
<input name="Amount" asp-for="#bidModel.Amount" />
</div>
</div>
Controller:
public async Task<IActionResult> AddBid(BidModel Bid)
{
var result = await _bidBusinessInterface.CreateBidAsync(Bid, Bid.AuctionId);
if (result)
{
ViewBag.Message = "Bud lagt!";
}
else
{
ViewBag.Message = "Bud förlågt!";
}
return PartialView("_BidCreatorPartial");
}
And then we have the modal where i want to rerender the partialview:
<div class="modal fade" id="bidModal" tabindex="-1" role="dialog" aria-labelledby="bidModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="bidModalLabel">Lägg bud</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="AddBid" asp-controller="Home" method="POST" data-ajax="true" data-ajax-update="frmBid">
<div id="frmBid">
<partial name="_BidCreatorPartial" model="#bidModel"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Avbryt</button>
<button type="submit" class="btn btn-primary">Spara</button>
</div>
</form>
</div>
</div>
</div>
</div>
As I said, what I want to accomplish is to rerender the form, so that the message can be shown in the modal.
What happens is it renders a whole white page with only the form and the message.
You didn't actually post your form itself, but my best guess is that you're just doing a standard old HTML form post. That's always going to cause the page to change, and then since you're only returning a partial view, and not a full view, your page gets replaced with just that snippet of HTML.
What you want requires AJAX. You need to catch the submit event on the form, and instead of letting it go as normal, you make an AJAX request with the form data serialized. Then, in the success callback of your AJAX request, you'll need to query the element you want to replace the HTML of from the DOM and change its innerHTML value to what's returned from the AJAX request.
Since an ASP.NET Core project comes with jQuery out of the box, I'm going to assume you can use that:
$('#MyForm').on('submit', function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
method: 'post',
data: $form.serialize(),
success: function (html) {
$('#frmBid').html(html);
}
});
});

How I can use html tags for input and submit in asp.net mvc 5 without Html.BeginForm?

net mvc 5 application and for this I use bootstrap because it looks fine.
I don't want to use for an input and a searchbutton the
#using (Html.BeginForm("...
Can I control the html tags without this from my controller. For example here is my index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
</div>
</div>
I want if I click on the Searchbutton I get a message with the text from the inputfield.
Here is the Controller:
public ActionResult Search(string value)
{
//listofUsers is a arraylist of all users that found^^
return View(listofUsers);
}
How I can do this? :)
Add a div to show the result:
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
<div class="custom-search-result"></div>
Then in a script tag or a linked js file:
$(document).ready(function () {
$('.custom-search-input').each(function () {
var sinput = $(this);
var svalue = sinput.find('input');
var sresult = sinput.next('.custom-search-result');
sinput.find('button').click(function () {
$.ajax({
url: '/ControllerName/Search?value=' + svalue.val(),
type: 'GET'
}).done(function (result) {
sresult.html(result);
});
});
});
});
This is a basic example with no error handling.
First I highly recommend reading Philip Walton (Google) - Decoupling your HTML, CSS and Javascript, it's extremely good.
Here how I would use MVC to it's full potential.
Model:
// Extensible Programming
// Using a string limits additional features
// Future proofing via a class that takes 2 minutes to create
public class GlobalSearch
{
public string SearchTerms { get; set; }
}
View:
#Model GlobalSearch
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
#using (Html.BeginForm("Search"))
{
<div class="input-group col-md-12">
#Html.TextBoxFor(m => m.SearchTerms, new {
#class="search-query form-control",
placeholder="Search" })
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search js-form-submit"></span>
</button>
</span>
</div>
}
</div>
</div>
</div>
Controller:
// Strongly Typed Class is Returned
public ActionResult Search(GlobalSearch search)
{
return View(listofUsers);
}
The following script will require this fantastic script called form2js which correctly converts any strongly-typed forms generated by MVC (arrays, lists etc) into Json that will be ModelBinded correctly.
$(document).ready(function() {
('.js-form-submit').on('click', function() {
var $form = $(this).closest('form');
var json = form2js($form);
var ajaxSettings = {
url: $form.attr('action'),
type: $form.attr('method'),
data: json,
contentType: "application/json",
}
$.ajax(ajaxSettings)
.done()
.always()
.fail();
});
});
Of course this could be easily abstract into it's own javascript class/namespace that returns the promise and reusable on any form that simply has a button with the class js-form-submit instead of continually rewriting $.ajax over and over again each time for different forms.

Categories