jquery submit form not working action is not working - javascript

Heading
I'm trying to build a submit form for my login, but I don't know why this action is not working. Any ideas ?
List item jquery
$(function() {
var $formLogin = $('#login-form');
var $formLost = $('#lost-form');
var $formRegister = $('#register-form');
var $divForms = $('#div-forms');
var $modalAnimateTime = 300;
var $msgAnimateTime = 150;
var $msgShowTime = 2000;
$("form").submit(function (e) {
e.preventDefault();
switch(this.id) {
case "login-form":
var $lg_username=$('#login_username').val();
var $lg_password=$('#login_password').val();
if ($lg_username == "ERROR") {
msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "error", "glyphicon-remove", "Login error");
} else {
msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "success", "glyphicon-ok", "Login OK");
}
return false;
break;
case "lost-form":
var $ls_email=$('#lost_email').val();
if ($ls_email == "ERROR") {
msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "error", "glyphicon-remove", "Send error");
} else {
msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "success", "glyphicon-ok", "Send OK");
}
return false;
break;
case "register-form":
var $rg_username=$('#register_username').val();
var $rg_email=$('#register_email').val();
var $rg_password=$('#register_password').val();
if ($rg_username == "ERROR") {
msgChange($('#div-register-msg'), $('#icon-register-msg'), $('#text-register-msg'), "error", "glyphicon-remove", "Register error");
} else {
msgChange($('#div-register-msg'), $('#icon-register-msg'), $('#text-register-msg'), "success", "glyphicon-ok", "Register OK");
}
return false;
break;
default:
return false;
}
return false;
});
$('#login_register_btn').click( function () { modalAnimate($formLogin, $formRegister) });
$('#register_login_btn').click( function () { modalAnimate($formRegister, $formLogin); });
$('#login_lost_btn').click( function () { modalAnimate($formLogin, $formLost); });
$('#lost_login_btn').click( function () { modalAnimate($formLost, $formLogin); });
$('#lost_register_btn').click( function () { modalAnimate($formLost, $formRegister); });
$('#register_lost_btn').click( function () { modalAnimate($formRegister, $formLost); });
function modalAnimate ($oldForm, $newForm) {
var $oldH = $oldForm.height();
var $newH = $newForm.height();
$divForms.css("height",$oldH);
$oldForm.fadeToggle($modalAnimateTime, function(){
$divForms.animate({height: $newH}, $modalAnimateTime, function(){
$newForm.fadeToggle($modalAnimateTime);
});
});
}
function msgFade ($msgId, $msgText) {
$msgId.fadeOut($msgAnimateTime, function() {
$(this).text($msgText).fadeIn($msgAnimateTime);
});
}
function msgChange($divTag, $iconTag, $textTag, $divClass, $iconClass, $msgText) {
var $msgOld = $divTag.text();
msgFade($textTag, $msgText);
$divTag.addClass($divClass);
$iconTag.removeClass("glyphicon-chevron-right");
$iconTag.addClass($iconClass + " " + $divClass);
setTimeout(function() {
msgFade($textTag, $msgOld);
$divTag.removeClass($divClass);
$iconTag.addClass("glyphicon-chevron-right");
$iconTag.removeClass($iconClass + " " + $divClass);
}, $msgShowTime);
}
});
List item html
<!-- Begin # DIV Form -->
<div id="div-forms">
<!-- Begin # Login Form -->
<form id="login-form" method="post" action="login.php">
<div class="modal-body">
<div id="div-login-msg">
<div id="icon-login-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-login-msg">Type your username and password.</span>
</div>
<input id="login_username" class="form-control" type="text" placeholder="Username (type ERROR for error effect)" required>
<input id="login_password" class="form-control" type="password" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
<div class="modal-footer">
<div>
<button type="submit" name="login" class="btn btn-primary btn-lg btn-block">Login</button>
</div>
<div>
<button id="login_lost_btn" type="button" class="btn btn-link">Lost Password?</button>
<button id="login_register_btn" type="button" class="btn btn-link">Register</button>
</div>
</div>
</form>
<!-- End # Login Form -->
<!-- Begin | Lost Password Form -->
<form id="lost-form" style="display:none;" method="post" action="submit.php">
<div class="modal-body">
<div id="div-lost-msg">
<div id="icon-lost-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-lost-msg">Type your e-mail.</span>
</div>
<input id="lost_email" class="form-control" type="text" placeholder="E-Mail (type ERROR for error effect)" required>
</div>
<div class="modal-footer">
<div>
<button type="submit" name="submit" class="btn btn-primary btn-lg btn-block">Send</button>
</div>
<div>
<button id="lost_login_btn" type="button" class="btn btn-link">Log In</button>
<button id="lost_register_btn" type="button" class="btn btn-link">Register</button>
</div>
</div>
</form>
<!-- End | Lost Password Form -->
<!-- Begin | Register Form -->
<form id="register-form" style="display:none;" method="post" action="submit.php">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Register an account.</span>
</div>
<input id="register_username" class="form-control" type="text" placeholder="Username (type ERROR for error effect)" required>
<input id="register_email" class="form-control" type="text" placeholder="E-Mail" required>
<input id="register_password" class="form-control" type="password" placeholder="Password" required>
</div>
<div class="modal-footer">
<div>
<button type="submit" name="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</div>
<div>
<button id="register_login_btn" type="button" class="btn btn-link">Log In</button>
<button id="register_lost_btn" type="button" class="btn btn-link">Lost Password?</button>
</div>
</div>
</form>
<!-- End | Register Form -->
</div>
<!-- End # DIV Form -->
</div>
</div>
</div>

You have to prevent your form from submitting first before you can run custom code, or else your form will submit before your code runs. This can be done by using e.preventDefault(). For example:
$("form").submit(function (e) {
e.preventDefault();
...
}

Related

Modal Pop-Up Not Passing iFormFile Data On JavaScript Ajax Intercept

This is sort of an add-on to my previous question:
Modal Pop-Up Not Closing Properly After Form Submission
I'm trying to reuse the modal pop-up functionality for another pop-up on the same page. This time I am using it to upload a file. This is the javascript in question:
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
})
I inadvertently misspelled "relative" on the submit button of this form:
#model Models.AttachmentModel
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Attachment">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success realative" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
<script type="text/javascript">
$(function () {
});
</script>
With the word "relative" misspelled, the file information is being sent to the action in the controller(see below). My guess is the Javscript isn't catching the click action ($('body').on('click', '.relative', function (e)). When I spell "relative" correctly the file information is NULL:
public async Task<IActionResult> FileUpload(IFormFile file, IFormCollection collection)
{ //do something
}
What needs to change with the Javascript (or my form/controller) to get the file information? In both cases the collection information is being passed. Is there a way to get the file information added to the collection?
--------- More Info based on #Rena answer
Let me expand some more on the original code and how this works. I have a page that has a modal section that will be populated with different partial views depending upon what I want displayed in the modal. On the Main page it has the following Javascript section:
<script>
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
})
$('body').on('click', '.close', function () {
$('body').find('#modal-container').modal('hide');
});
$('#CancelModal').on('click', function () {
return false;
});
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
I took what was provided by #Rena and inserted it into this section, but found that the Modal wouldn't close (although the data from the form in the partial view was now getting passed). I tried changing the .realative to another value on both the partial view and the javascript, but it made no difference. I then tried what #mj313 suggested in the preceding posts by changing the provided script like this to redirect to /Issue/Edit but that didn't work either.:
}).done((response, textStatus, xhr) => {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
So while I can now pass data I can't close the Modal.
UPDATE
Here is a slimmed down version of the Edit page where all of this starts
#model MYAPP.ViewModels.IssueViewModel
#{
ViewData["Title"] = "Issue Detail Page";
}
<script type="text/javascript">
$(document).ready(function () {
$("#UploadSection").load("/Attachment/GetAttachments/" + #Model.IssueData.issueId);
});
$(function () {
//Some code
});
function onSelectChange(element) {
//Some code
}
</script>
<div asp-validation-summary="All" class="text-danger"></div>
<hr />
<div class="row">
<div>
<form asp-action="Edit">
<input type="hidden" asp-for="IssueData.issueId" />
#*Some Code*#
#*Placeholder for Modal Pop-up*#
<div id="modal-container" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
#*This table contains the first control that generates a modal which contains the _CreateEdit.cshtml*#
<table width="100%">
<tr>
<td width="90%" style="padding:5px 5px 0px 5px;background-color:midnightblue;color:white">
<div class="form-group">
<label asp-for="IssueData.issueStatus" class="control-label">Current Issue Status</label>
-
#if (#Model.IssueData.StatusList[0].UpdatedByName != "")
{
<text>Updated by: </text> #Model.IssueData.StatusList[0].UpdatedByName <text> - </text>#Model.IssueData.StatusList[0].StatusDate.Value.ToShortDateString()
}
else
{
<text>Created by: </text> #Model.IssueData.StatusList[0].EnteredByName <text> - </text>#Model.IssueData.StatusList[0].StatusDate.Value.ToShortDateString()
}
</div>
</td>
<td style="background-color: midnightblue; padding-right:5px">
#if (#Model.IssueData.StatusList[0].StatusDate != DateTime.Today)
{
Add New Status
}
else
{
<a href="#Url.Action("CreateEdit", new { controller = "Issue", issueid = Model.IssueData.issueId, addedit = "edit" })"
class="modal-link btn btn-success">Edit Current Status</a>
}
</td>
</tr>
</table>
<br />
#*This table contains the second control that generates a modal which contains the _UploadFile.cshtml*#
<table id="upload" width="100%">
<tr>
<td width="90%" style="padding:5px 5px 0px 5px;background-color:midnightblue;color:white">
<label class="control-label">Upload Attachments</label>
</td>
<td style="background-color: midnightblue; padding-right:5px">
<a href="#Url.Action("FileUpload", new { controller = "Attachment", issueid = Model.IssueData.issueId })"
class="modal-link btn btn-success">Upload Files</a>
</td>
</tr>
</table>
#*This section contains a partial view _DisplayFiles.cshtml. The _DisplayFiles.cshtml has controls that generate 2 more modals. The modals contain either the
_DeleteFile.cshtml or _EditFile.cshtml partial views*#
<div id="UploadSection"></div>
#{
await Html.RenderPartialAsync("_DisplayFiles");
}
<div class="form-group">
<input type="submit" value="Save Changes" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
//Using this to scroll the page on the close of the modal/page refresh
$(document).ready(function () {
var JumpTo = '#ViewBag.JumpToDivId';
if (JumpTo != "") {
$(this).scrollTop($('#' + JumpTo).position().top);
}
});
//Using this to Capture the click that opens the modals
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
//Using this to Capture the click that Submits the _EditFile,_DeleteFile,_CreateEdit forms on the modal
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
var issueid = "";
issueid = $('body').find('[name="issueidSaved"]').val();
var jumpto = $('body').find('[name="jumpto"]').val();
if (isValid) {
$('body').find('#modal-container').modal('hide');
if (issueid == "")
{
window.location.href = "/Issue/Edit/?id=" + issueid + "&jumpto=" + jumpto;
}
}
});
})
//Using this to Capture the click that Submits the _UploadFile form on the modal
$(function () {
$('body').on('click', '.fileupload', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var fdata = new FormData();
$('input[name="file"]').each(function (a, b) {
var fileInput = $('input[name="file"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("file", file);
}
});
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
var isValid = $(response).find('[name="IsValid"]').val() == 'True';
var issueid = $(response).find('[name="issueidSaved"]').val();
var jumpto = $(response).find('[name="jumpto"]').val();
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit/?id=" + issueid + "&jumpto="+jumpto;
}
});
})
});
$('body').on('click', '.close', function () {
$('body').find('#modal-container').modal('hide');
});
$('#CancelModal').on('click', function () {
return false;
});
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
}
Here is the code for _UpdateFile.cshtml
#model MYAPP.Models.AttachmentModel
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<input name="issueidSaved" type="hidden" value="#ViewBag.ID" />
<input name="jumpto" type="hidden" value="#ViewBag.JumpToDivId" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Attachment">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success fileupload" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
<script type="text/javascript">
$(function () {
});
</script>
<!--Modal Body End-->
Here is the code for the file Upload
[HttpPost]
public async Task<IActionResult> FileUpload(IFormFile file, IFormCollection collection)
{
if (file == null)
{
ModelState.AddModelError("aFileData", "Please select a file.");
}
if (collection["aIssueAttachmentDescription"] == "")
{
ModelState.AddModelError("aIssueAttachmentDescription", "Please provide a description for the file.");
}
if (!ModelState.IsValid)
{
return PartialView("_UploadFile");
}
var formFileContent =
await FileHelpers.ProcessFormFile<BufferedSingleFileUploadDb>(
file, ModelState, _permittedExtensions,
_fileSizeLimit);
var thefile = new AttachmentModel
{
aFileData = formFileContent,
aFileName = file.FileName,
aIssueAttachmentDescription = collection["aIssueAttachmentDescription"],
aFileSize = file.Length,
aFileType=file.ContentType,
issueId = collection["issueId"]
};
string result = _adoSqlService.InsertFile(thefile);
ViewBag.ID = collection["issueId"];
ViewBag.JumpToDivId = "upload";
return PartialView("_UploadFile");
}
You can see in the code above that I add in model errors if the file is not selected or the description is not filled in. These are not being shown.
I can live with the collection returning the entire Edit forms data, but ideally it should only return the fields on the _UploadFile.cshtml form (aIssueAttachmentDescription, issueId)
Anything you can provide that fixes the display of the model errors as well as a way to simplify my code would be greatly appreciated.
With the word "relative" misspelled, the file information is being sent to the action in the controller(see below). My guess is the Javscript isn't catching the click action ($('body').on('click', '.relative', function (e)). When I spell "relative" correctly the file information is NULL
The <input type="submit"> defines a submit button which submits all form values to a form-handler.So although you misspelled the word,it also could submit to the action successfully by default.
For how to use ajax to pass form data with file,you could follow:
#model Mvc3_0.Controllers.HomeController.AttachmentModel
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Attachment">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success realative" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$('body').on('click', '.realative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var fdata = new FormData();
$('input[name="file"]').each(function (a, b) {
var fileInput = $('input[name="file"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("file", file);
}
});
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
$("#exampleModal").modal('hide'); //update here...
});
})
});
</script>
}
Update1:
.done((response, textStatus, xhr) => {
$("#exampleModal").modal('hide'); //update here...
});
Update2:
By using your code,I find that you add the modal html in a form which is in the main page.This will cause the form in modal which is in _UploadFile.cshtml could not generate well in my project.Here is the whole working demo:
Main Page:
#model AttachmentModel
<div class="row">
<div>
//change here.....
<div id="modal-container" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
<form asp-action="Edit">
<br />
#*This table contains the second control that generates a modal which contains the _UploadFile.cshtml*#
<table id="upload" width="100%">
<tr>
<td width="90%" style="padding:5px 5px 0px 5px;background-color:midnightblue;color:white">
<label class="control-label">Upload Attachments</label>
</td>
<td style="background-color: midnightblue; padding-right:5px">
<a href="#Url.Action("FileUpload", new { controller = "Attachment", issueid = "1" })"
class="modal-link btn btn-success">Upload Files</a>
</td>
</tr>
</table>
<div class="form-group">
<input type="submit" value="Save Changes" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Js in Main Page:
#section Scripts
{
<script type="text/javascript">
$(function () {
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$('body').on('click', '.fileupload', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var fdata = new FormData();
$('input[name="file"]').each(function (a, b) {
var fileInput = $('input[name="file"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("file", file);
}
});
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
})
.done((response, textStatus, xhr) => {
var isValid = $(response).find('[name="IsValid"]').val() == 'True';
var issueid = $(response).find('[name="issueidSaved"]').val();
var jumpto = $(response).find('[name="jumpto"]').val();
if (isValid) {
$('body').find('#modal-container').modal('hide');
}
});
})
})
</script>
}
_UploadFile.cshtml:
#model AttachmentModel
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<input name="issueidSaved" type="hidden" value="#ViewBag.ID" />
<input name="jumpto" type="hidden" value="#ViewBag.JumpToDivId" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Home">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success fileupload" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
Controller:
[HttpPost]
public async Task<IActionResult> FileUpload(IFormFile file, IFormCollection collection)
{
var thefile = new AttachmentModel
{
aFileData = "asdad",
aIssueAttachmentDescription = collection["aIssueAttachmentDescription"],
issueId = collection["issueId"]
};
ViewBag.ID = collection["issueId"];
ViewBag.JumpToDivId = "upload";
return PartialView("_UploadFile");
}
Result:

Manipulating element by ID

I'm creating a plugin for Input Files, I created everything but without having in mind the possibility of having multiple inputs on screen, then it was necessary instead to manipulate the element from the element ID. This is so that actions in one input do not affect all other inputs on the screen.
Below is the code so far, I could not make it work when informed by the element ID.
function bs_input_file() {
// TODO: add function to hide remove button when file not informed
const inputElement = $(".input-file").find('input');
const inputId = inputElement.map(function (index, dom) {
return dom.id
});
buttonInspec(inputId);
function buttonInspec(id) {
$("#" + id).find("button.btn-reset").addClass("hidden");
var element = $("#" + id).find('input');
element.on("change input propertychange", function() {
console.log("changed!")
if (element.val() != "") {
$("#" + id).find("button.btn-reset").removeClass("hidden");
}
});
}
// Necessary to put ID below also
$(".input-file").before(
function() {
if (!$(this).prev().hasClass('input-ghost')) {
var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
element.attr("name", $(this).attr("name"));
element.change(function() {
element.next(element).find('input').val((element.val()).split('\\').pop());
});
$(this).find("button.btn-choose").click(function() {
element.click();
});
$(this).find("button.btn-reset").click(function() {
element.val(null);
$(this).parents(".input-file").find('input').val('');
});
$(this).find('input').css("cursor", "pointer");
$(this).find('input').mousedown(function() {
$(this).parents('.input-file').prev().click();
return false;
});
return element;
}
}
);
}
bs_input_file();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h3>Example</h3>
<form method="POST" action="#" enctype="multipart/form-data">
<!-- COMPONENT START -->
<div class="form-group">
<div class="input-group input-file" name="Fichier1">
<input id="fileInput0" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group input-file" name="Fichier2">
<input id="fileInput1" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<!-- COMPONENT END -->
</form>
</div>
</div>

login form validation javascript - value not present in $_POST

I am trying to validate the form with id's username and initial_password: The HTML portion is as:
<form name="myform" action="includes/logincontrol.php" method="POST" onsubmit="return validateForm()">
<div class="form-group"> <!-- User ID Field -->
<label id="user_name_error" >User ID:</label>
<input class="form-control" id="username" type="text" onfocusout ="validateUserName()"/>
</div>
<div class="form-group"> <!-- Password Field -->
<label id="password_error">Password: </label>
<input class="form-control" id="initial_password" type="password" onfocusout ="validatePassword()"/>
</div>
<div class="form-group"> <!-- Register -->
<p id="submit-error"></p>
<hr/>
<button class="btn btn-primary" id="login" type="submit">Login</button>
<input class="btn btn-danger" type="reset" value="Reset" onClick="clearfunc()"/>
<hr/>
<button type="button" class="btn btn-success" onclick="window.location.href = 'register_user.php'">Register</button>
<button type="button" class="btn btn-warning" onclick="window.location.href = 'changepw.php'">Change Password</button>
</div>
</form>
Java Script:
function validateUserName() {
var user_name_entered = document.getElementById('username').value;
if (user_name_entered.length === 0) {
producePrompt('User empty?', 'user_name_error', 'red');
document.getElementById('login').disabled = true;
return false;
}
producePrompt('User Name OK!', 'user_name_error', 'green');
document.getElementById('login').disabled = false;
return true;
}
function validatePassword() {
var password_entered = document.getElementById('initial_password').value;
if (password_entered.length === 0) {
producePrompt('Password empty?', 'password_error', 'red');
document.getElementById('login').disabled = true;
return false;
}
producePrompt('Password Entered!', 'password_error', 'green');
document.getElementById('login').disabled = false;
return true;
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
I am unable to get the elements in $_POST array. Please help
You have to put name at inputs, to access them with $_POST.
<input name="usernameInput" class="form-control" id="username" type="text" onfocusout ="validateUserName()"/>
<?php
$username = $_POST['usernameInput'];
?>
If you want to see if the form is submited put a name in the type submit input and try this:
if (isset($_POST['submitButton']) {
$username = $_POST['usernameInput'];
#..etc
}

Jquery - Getting a parent element's data-id

been looking through previously asked questions but can't find much help.
I have the following html code that sends through a data-id to the following modal, when the user submits the form i have created a ('#edit-form').submit function which needs to send through the previously mentioned data-id.
Here's my code
Button to Open Modal >>
<button type="button" class="edit-group" title="Edit Group" data-id="<?php echo $group->id ?>" data-name="<?php echo $group->groupName ?>">Edit Group</button>
Form inside modal:
<form class="form-horizontal" id="edit-template-form">
<div class="modal-body">
<div class="form-group">
<label for="edit-group-name" class="col-sm-2 control-label">Group name</label>
<div class="col-sm-10">
<input type="text" name="groupName" class="form-control" id="edit-template-name" placeholder="New Group Name">
</div>
</div>
<input type="hidden" id="edit-template-id">
</div>
<div class="modal-footer">
<button type="button" class="md-close" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary btn-flat">Save Changes</button>
</div>
</form>
Jquery
$('#edit-template-form').submit(function (e) {
e.preventDefault();
var data = {
id: $(this).parent().val($(this).data('id')),
name: $('#edit-template-name').val()
};
console.log(data);
return false;
});
this keyword refers to data object itself not #edit-template-form. So store the variable this before using it like below:
$('#edit-template-form').submit(function (e) {
e.preventDefault();
var form = $(this);
var data = {
id: form.parent().val(form.data('id')),
name: $('#edit-template-name').val()
};
console.log(data);
return false;
});

field empty error for pop-up form

Can I have yout help pleas there,I make a validation field for a popup form :
function prepareEventHandlers() {
document.getElementById("contact").onsubmit = function () {
if (document.getElementById("message").value == '') {
document.getElementById("errorMessage").innerHTML = 'the field should not be empty!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
then the html code :
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-body">
<form class="contact" name="contact" >
<label class="label" for="message">Enter a Message</label><br>
<textarea id="message" name="message" class="input-xlarge"></textarea>
<p><span id="errorMessage"></span></p>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
No!
</div>
and I got this error :
TypeError: document.getElementById(...) is null document.getElementById("contact").onsubmit = function () {
Any Idea?
Edit:
OK I add id="contact" to my form so the error is gone but now the popup form is displyaed but when I try to click send with empty or not empty value nothing is happened...
just close </form> after <input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
and change html form id to contact

Categories

Resources