File is stored couple of times instead of once - javascript

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".

Related

How get clicked id when clicked element in modal window?

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'); });

why my modal is not closing on clicking add area button

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.

How do I remove a .html in javascript?

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);

CKEditor is not working with bootstrap modal

I want to show ckEditor on bootstrap modal but the ckEditor is not opening as shown below. After searching through the internet I have got some solution in a different way like this link but I will perform an ajax request hence I have to open the modal using $('.cia_modal').modal('toggle'). The above-mentioned solution link does not work for me
Modal Button:
<button class="btn btn-info btn-xs cia_modal_btn" data-id="<?php echo $post->post_id; ?>" data-table="post" data-attr="post_id">
Create New Post
</button>
Modal:
<!--Modal-->
<div class="modal fade cia_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">Create New Post</h4>
</div>
<div class="modal-body">
<form action="/action_page.php">
<div class="form-group">
<textarea class="ck_editor" name="post" id="" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--End Modal-->
Javascript:
<script type="text/javascript">
$(document).on("click", ".modal_btn", function (e) {
e.preventDefault();
e.stopPropagation();
let cia_modal = $('.cia_modal');
//Set modal show/hide
cia_modal.modal('toggle');
let id = $(this).attr('data-id');
let table = $(this).attr('data-table');
let attr = $(this).attr('data-attr');
//Set Form Data
let formData = new FormData();
formData.append('id',id);
formData.append('table',table);
formData.append('attr',attr);
$.ajax({
type: 'post',
url: '<?php echo base_url()?>post/create_post',
data: formData,
contentType: false,
processData: false,
success: function (data) {
//
}
});
});
</script>
Please help me. Thanks
I assume, you are using CKEditor 4.x.
You need to create editor using CKEDITOR.replace( 'ck_editor' ), you can do it only on element that is existing inside document. It doesn't matter if it's hidden or not. If your modal is inside DOM, but hidden, then just initialize editor. Otherwise you need to wait until element is appended then call CKEDITOR.replace.
Depending on how bootstraps implements modal.show. If it's just changes CSS to make it visible, then most likely you can initialize editor at the start of your script, if it adds elements to document, then you need to use some of bootstrap events to create editor in right time. See shown.bs.modal: https://getbootstrap.com/docs/4.0/components/modal/#events
Just initialize the editor:
<script type="text/javascript">
ClassicEditor.create($('.ck_editor')[0])
.then( editor => {
console.log( editor );
})
.catch( error => {
console.log( error );
});
$(document).on("click", ".modal_btn", function (e) {
//....

Get form values and pass it to Bootstrap modal on Submit

I'm trying to get my form data and pass it as JSON to my modal dialog, which also should open on Submit button!
Here is what I've done so far:
HTML
<form class="form-horizontal" id="configuration-form">
--unimportant--
<button type="submit" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please copy this code to your HTML</h4>
</div>
<div class="modal-body">
<code id="configurationObject"></code><br/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
(function(formId) {
$("#" + formId).submit(function(event){
event.preventDefault();
var errMsg = "Something went wrong with form submit, please try again";
var json = convertFormToJSON(this); //here I got my json object with all my form data
$.ajax({
type : 'POST',
data: {conf: JSON.stringify(json)},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data){
$("#configurationObject").html(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
return false;
});
})("configuration-form");
After Submit button is clicked I do get my JSON object with form data (I can log it after
var json = convertFormToJSON(this)
and my modal dialog window is opened, but I do miss my data aka.
element with id="configurationObject" is empty.
Thanks in advance
Have you tried to append() the data to #configurationObject rather than using html()?
According to documentation $.html() accepts A string of HTML to set as the content of each matched element. .
Here you are passing json data instead of string. So first, you have to convert json response to string. $("#configurationObject").html(JSON.stringify(data));
or you can use
$("#configurationObject").append(data);

Categories

Resources