Hello guys I need help to remove a span after being successful in ajax.
I am inserting a loading when pressing, the save button so that the user does not keep pressing several times and ends up passing the same item several times, but after success it returns without the old way
follows an excerpt from the code where I'm using this function
$('#btn_salvar_consultor').prop("disabled", true);
// Adicionar loading no botão
$('#btn_salvar_consultor').html(
`<span id="loading_consultor" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>`
);
var Consultor = $('#consultor').val();
var justificativaconsultor = $('#justificativaconsultor').val();
$.ajax({
url: '#Url.Action("AdicionarConsultor", "Oportunidade")',
data: {
id_usuario_responsavel: Consultor,
id_oportunidade: id_oportunidade,
justificativaconsultor: justificativaconsultor
},
type: 'POST',
success: function(data) {
$('#AddConsutlorResponsavel').modal('hide');
$.ajax({
url: '#Url.Action("_PartialOportunidadeTimeline", "Oportunidade")',
data: {
id_oportunidade: id_oportunidade
},
type: 'POST',
success: function(data) {
$('#btn_salvar_consultor').prop("disabled", false);
$('#loading_consultor').remove()
$('#consultor').val("0");
$('#justificativaconsultor').val("");
$("#partinal_container-fluid").html(data);
}
});
},
error: function(xhr, status, error) {
swal({
title: 'Ops!',
text: error,
icon: 'error',
timer: 10000,
button: 'OK!'
});
$('#btn_salvar_consultor').prop("disabled", false);
$('#loading_consultor').remove();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal fade" id="AddConsutlorResponsavel" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" style="box-shadow: 0 0 1em black; border:solid 1px">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Selecione o consultor</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="partinal_container-fluid" class="modal-body">
<div class="row">
<select id="consultor" class="form-control" data-val="true" name="consultor">
<option value="0">[Selecione...]</option>
#foreach (var item in ViewBag.Consultor) {
<option value="#item.UsuarioId">#item.NomeCompleto</option>
}
</select>
</div>
<div class="row">
<label class="col-form-label">Justificativa</label>
<textarea id="justificativaconsultor" class="form-control"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="btn_salvar_consultor" onclick="AddConsultor()">Salvar</button>
</div>
</div>
</div>
</div>
Solution
I realized that when I remove the span it removes the text, it follows the correction after success or error in ajax.
$('#btn_salvar_consultor').prop("disabled", false).text("Salvar");
instead of
$('#btn_salvar_consultor').prop("disabled", false);
Related
I am beginner web developer.
I have code to dynamic load data to iframe:
$(document).ready(function () {
function loadMaterials(type, query) {
$.ajax({
type: 'GET',
url: '/getMaterials',
dataType: "text",
data: {
query: query,
type: type,
},
success: function (data) {
$('.dynamic-materials').html(data);
}
});
}
$('.product-material-front').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(2, "");
$('.select-material-title').html('MateriaĹ frontu')
$('.material-type-input').val(2);
$('#material-dialog-modal').modal('show');
});
$('.product-material-body').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(1, "");
$('.select-material-title').html('MateriaĹ korpusu');
$('.material-type-input').val(1);
$('#material-dialog-modal').modal('show');
});
});
<div id="material-dialog-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body pt-0">
<h3 class="select-material-title px-3"></h3>
<form method="get" action="{{ route('frontend.get.materials') }}" class="px-3 select-material-url">
<input type="hidden" name="type" value="" class="material-type-input">
<div class="inner-addon rounded-0 modal-search-form">
<i class="fa fa-search"></i>
<input type="text" class="form-control product-query-string-body"
placeholder="Szukaj produktu"
aria-label="Wpisz nazwę lub kod koloru"/>
</div>
</form>
<div class="row material-list px-5 pt-4 dynamic-materials">
</div>
</div>
</div>
</div>
</div>
It's work fine.
I need to change the classes of the clicked elements.
Additionally, I want to select select with the option selected.
I made a code like this:
$('.select-material-body').on('click', function(e){ console.log('ok');
if($('.material-type-input').val() == 1){
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-body]').val($(this).attr('id'));
$('.product-material-body').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
} else{
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-front]').val($(this).attr('id'));
$('.product-material-front').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
}
});
But unfortunately it doesn't work :(
How can i repair it?
My preview: http://serwer1356363.home.pl/_nauka/ - popup is visible after click select (with icon)
Please help me..
Since the modal content isn't append on the document, you can't bind event to it.
Instead, you can add an on() event to the body, passing your sub-selector :
$('body').on('click', '.select-material-body', function(e) { console.log('ok'); });
on click add area button my modal should be closed but it is not working. everything looks fine but i can not find error. id="category-popup" should close modal by $("#category-popup").modal('hide'); but it is not working can someone help me?
<div class="modal fade" id="category-popup" tabindex="-1" role="dialog" aria-labelledby="category-
popup" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Area</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="{{ route("save.area.ajax") }}" class="category-form">
{{ csrf_field() }}
<div class="form-group">
<label>Area Name</label>
<input type="text" name="name" class="form-control old-category" required="">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary btn-block add-area-submit-btn">Add
Area</button>
</div>
</form>
</div>
</div>
</div>
</div>
java script
$('.add-category').click(function(event){
event.preventDefault();
$('.old-category').val('')
$('.category-form').attr('action' , '{{ route("save.area.ajax") }}');
$('#category-popup .modal-title').html('Add Area');
$('#category-popup .modal-footer button').text('Add Area');
});
$(document).on('click', '.add-area-submit-btn', function(e){
e.preventDefault();
var btn = $(this);
if($('.category-form .old-category').val() != ""){
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res){
$("#area-select").html(res);
$("#category-popup").modal('hide');
}
});
}
});
The syntax for hiding modal is correct but please make sure that your $.ajax request is succeeding. Try doing console.log() in $.ajax success. Or add error in your ajax so you could know the error
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res) {
console.log("ajax request success");
$("#area-select").html(res);
$("#category-popup").modal('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ajax request failed: " + errorThrown);
}
});
check errors in the cnsole it submit area in option field but not closed
Hm, weird, are you sure you include jQuery correctly? Could you show your included scripts?
jQuery should be like: <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
In JavaScript one error results in broking whole script. And without jQuery your "modal" action will not work. I think it's the reason why your script not working.
When I upload a file it is stored X times where X is the time count you upload it. If I try to upload it three times in a row it will store one file, two files, three files which gives us 6 in total.
Why does that happen?
$(function() {
$("#uploadButton").on('click', function() {
const job_id = $(this).attr("data-item");
$("#cvForm").submit(function(e) {
e.preventDefault();
var form_data = new FormData(document.getElementById("cvForm"));
axios({
method: 'post',
url: '/job/apply/' + job_id,
data: form_data,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
});
return false;
});
});
});
Form is:
<div class="modal fade" id="CVModalUpload" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="cvForm" name="cv" method="post" action="{{ path('student_candidate', {'id':job.id}) }}" enctype="multipart/form-data">
<div class="input-group">
<div class="custom-file">
<input type="file" name="cv[file]" class="custom-file-input" id="uploadGroup" aria-describedby="uploadButton">
<label class="custom-file-label" for="uploadGroup">Choose CV</label>
</div>
<div class="input-group-append">
<button type="submit" name="cv[send]" class="btn btn btn-primary shadow rounded-0" id="uploadButton" data-item="{{ job.id }}">Upload CV</button>
</div>
</div>
{{ form_row(form._token) }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The issue is because you're nesting your event handlers. To fix this move submit() outside of click().
That said, now that you've added the HTML to the question, I can see that you don't need the click handler at all. You can simply read the data-item from the button when the form is submit. Try this:
jQuery(function($) {
$("#cvForm").submit(function(e) {
e.preventDefault();
let form_data = new FormData(this); // note 'this' here
let job_id = $('#uploadButton').data('item'); // note 'data()' here
axios({
method: 'post',
url: '/job/apply/' + job_id,
data: form_data,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
});
});
});
Its propably because of the location where you implemented submit(). You should propably move it outside of the click()-eventHandler.
That's because you have placed your submit button inside a form. Now whenever a button is pressed inside a form, it automatically submits the form. In your case form is submitting two times, once when button is clicked and second time inside your click handler.
Easy solution to this is, just change type attribute of your submit button to "button".
I have a JSP page,say xyz.jsp. I have a button called "send Mail" that has it's onclick() property set to a script function called sendMail(). Sending mail includes sending html data to the controller for generating PDF for which I am using Ajax. Now after the mail is sent successfully ,i want to show a pop-up indicating success. So on Ajax success i want to trigger the popup.
I am using bootstrap modal for popup.
This is my code for button and modal:
<div id="reportbuttons">
<button type="button" class="btn bg-red waves-effect" onclick="convertToPdf()" style="margin-right: 5px;float: right; margin-top: -8px">Download</button>
<button type="button" class="btn bg-red waves-effect" onclick="sendMail()" style="margin-right: 5px;float: right; margin-top: -8px">Send Mail</button>
<!-- Modal -->
<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">
<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>
And, this is my script:
<script>
function sendMail() {
let doc = new jsPDF('p','pt','a4');
doc.setProperties({
title: 'PDF Document',
subject: 'subject',
author: 'ABC',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'XYZ'
});
//document.getElementById('reportbuttons').remove();
document.getElementById('reportbuttons').style.display ="none";
doc.addHTML(document.body, function() {
var data = doc.output('datauristring');
var reqJson = {};
reqJson.machineId = "<%=machineId%>";
reqJson.monthYear = "<%=monthYear%>";
reqJson.data = data;
$.ajax(
{
url : "sendMail/",
type: "POST",
dataType: 'json',
data : JSON.stringify(reqJson),
contentType: "application/json",
success:function(data)
{
$("#myModal").modal();
alert('mail sent successfully');
document.getElementById('reportbuttons').style.display ="block";
},
error: function(data)
{
document.getElementById('reportbuttons').style.display ="block";
}
});
});
}
</script>
I want to show the bootstrap modal popup after the mail is succesfully sent or in other words on Ajax success.
Hello I am trying to call a method with parameters in my controller using ajax and jquery
Controller:
[HttpPost("{Id}")]
public ActionResult PostComment(int Id, ShowViewModel model)
{
}
View:
I have a button called AddComment, when clicked it should open a modal popup which asks for confirmation to save
<form id="addCommentForm" asp-action="postcomment" enctype="multipart/form-data">
<button id="addCommentButton" class="btn btn-primary">
<i class="fa fa-search"></i> Add comment
</button>`
<div class="modal fade" id="saveConfirmationDialog" tabindex="-1" role="dialog" aria-labelledby="saveConfirmationDialogTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="saveConfirmationDialogTitle">Post selective exchange comment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you want to post a comment?
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">
<i class="fa fa-envelope-open"></i> Post selective exchange comment
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">
<i class="fa fa-ban"></i> Close
</button>
</div>
</div>
</div>
</div>
</form>
Javascript:
ControllerName.View.Properties.controllerViewUrl = $("#controllerViewUrl").val();
$(document).ready(function () {
ControllerName.View.Validation.initialize();
ControllerName.View.Initialize.addCommentButton();
});
ControllerName.View.Initialize = {}
ControllerName.View.Initialize.addCommentButton = function () {
$('#addCommentButton').click(function (event) {
event.preventDefault();
if ($('#addCommentForm').valid()) {
$("#saveConfirmationDialog").modal('show');
}
});
}
ControllerName.View.Validation = {}
ControllerName.View.Validation.initialize = function () {
$("#addCommentForm").validate();
}
ControllerName.View.Ajax = {}
ControllerName.View.Ajax.postComment = function (successCallback) {
var url = ControllerName.View.Properties.controllerViewUrl + '/PostComment'+<<parameter>>;
}
My Controller method is not getting called, what am I doing wrong?
I also need to pass a Id as parameter
Please help, Thanks in advance
A simple example
HTML CODE
<button id="saveButton" type="button" data-toggle="modal" data-target="#saveConfirmationDialog" class="btn btn-labeled btn-danger" style="display:none;">Save Data</button>
<div id="saveConfirmationDialog" class="modal fade" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 id="modal-title" class="modal-title">Post selective exchange comment</h4>
</div>
<div class="modal-body">
Do you want to post a comment?
</div>
<div class="modal-footer">
<div id="formDiv">
<button id="sender" type="submit" class="btn btn-success"><i class="fa fa-envelope-open"></i> Post selective exchange comment</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-ban"></i> Close</button>
</div>
<div id="loadingPanel" style="display:none;">Loading...</div>
</div>
</div>
</div>
</div>
JS CODE
<script type="text/javascript">
$('#sender').click(function () {
PostDataToController();
});
function PostDataToController(action) {
$('#formDiv').hide();
$('#loadingPanel').show();
// create form data
var formData = new FormData();
formData.append("YourParameter", $('#YourValue').val());
// Write here your parameters what you need
// do post
$.ajax({
type: "POST",
url: "/localhost:8080/InsertComment",
enctype: "multipart/form-data",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (d) {
$('#formDiv').show();
$('#loadingPanel').hide();
if (d.result == "ok") {
/*Your success operations*/
}
else {
//alert(d.msg);
/*Your custom error operations*/
}
},
error: function (xhr, textStatus, errorThrown) {
/*Your error operations*/
//alert(xhr);
$('#formDiv').show();
$('#loadingPanel').hide();
}
});
}
</script>
MVC CODE
[HttpPost]
public ActionResult InsertComment(int Id, ShowViewModel model)
{
if (ModelState.IsValid)
{
// insert
// Yor save method is here
if (!isSuccess()) // your process not succeeded
{
// error
return Json(new { result = "no", msg = /*your error message*/ });
}
//succeeded
return Json(new { result = "ok" });
}
else
{
// error
string error = ModelState.Values.FirstOrDefault(f => f.Errors.Count > 0).Errors.FirstOrDefault().ErrorMessage;
return Json(new { result = "no", msg = error });
}
}