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);
Related
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.
I have table in modal with edit button to update the user details
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">User Info</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form>
<div class="modal-body edit-info" >
</div>
<div class="modal-footer">
<button type="submit" class="roomupdate btn btn-warning">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
and my ajax code is
$(document).on('click', '.roomupdate', function(){
ev.preventDefault();
$id= $('#id').val();
$building=$('#building').val();
$floorno=$('#floorno').val();
$roomno=$('#roomno').val();
$priority=$('#priority1').val();
$nobeds=$('#nobeds').val();
$('#editModal').modal('hide');
$.ajax({
type: "POST",
url: "addroomlist.php",
async: false,
data: {
building: $building,
id: $id,
floorno: $floorno,
roomno: $roomno,
priority: $priority,
nobeds: $nobeds,
roomupdate: 1,
},
success: function(){
showUser();
},
});
});
and my edit button code to call modal with user info.
<td> <button data-id='<?php echo $row['id'] ?>' class='roomedit btn btn-warning'>Edit</button></td>
when i first click save button after modify the details its working fine and modal closed with
$('#editModal').Modal('hide');
when i click edit button second time Modal not show up until i reload the page.
where it went wrong please help
In your ajax code remove $('#editModal').modal('hide'); from the line where you are using right now and put it in success function of ajax.
Like:
success: function(){
$('#editModal').modal('hide');
showUser();},
and if you are using location.reload(); in your showUser(); function then it will work but as far i know i think you did not add it in showUser(); so add also location.reload(); after showUser(); function or at the end of code written in showUser(); function.
And one more thing do you write any code by which clicking on edit button the modal should open in javascript?
I got a problem with foreach loop. What am i trying to do is get data (JsonResult) from action in controller. Get get songs for each album.
public JsonResult SongListByAlbum(int albumID)
{
var songs = (from song in Song.GetSongList()
join album in Album.GetAlbumList()
on song.AlbumID equals album.AlbumID
where (albumID == album.AlbumID)
select song).ToList();
return Json(songs,JsonRequestBehavior.AllowGet);
}
Then put them into view, for album get list of songs and show them as modals
There is my view:
#foreach (var item in Model.Albums){
<button id="#item.AlbumID" type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-#item.AlbumID">
Show
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal-#item.AlbumID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-#item.AlbumID" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel-#item.AlbumID">#item.AlbumName #item.Year, #item.BandName</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="parent" class="modal-body">
</div>
<div class="modal-footer">
<button id="closeModal"type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
And there is a script, where I get songs for each album.
<script>
$(".myModals").on("click", function () {
var Id = $(this).attr('id');
alert(Id);
$.ajax({
type: "GET",
url: '#Url.RouteUrl(new{ action= "SongListByAlbum", controller="Default"})',
data: {albumID:Id},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
for (var i in result) {
$('#parent').append('<p class="toRemove">' + result[i].SongName + '</p>');
}
},
error: function (response) {
alert('error');
}
});
});
</script>
The problem is : when i click on the first modal button everything is fine, i get what i want to. But when i click on the second one i got empty modal. Then when i click again on the first one i got data from previous click and penultimate. Image: enter image description here
To avoid multiple <div id="parent"> elements, you should probably assign the Id the same way you do for the buttons. Like <div id="parent-#item.AlbumID">. Then in your ajax call reference the correct div. $('#parent-' + Id).
Not sure if that is your only probably, but might get you closer.
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) {
//....
Demo and full code is like this : https://jsfiddle.net/oscar11/o5qn5gum/5/
My HTML code is like this :
<button type="button">Click Me</button>
<div id="tes">
</div>
<!-- Modal Currency-->
<div class="modal fade" id="priceModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
My Javascript code is like this :
$(document).ready(function(){
$("button").click(function(){
$.ajax({
//type: 'POST',
//url: 'script.php',
success: function(data) {
// alert(data);
// $("p").text(data);
var priceModal1 = '[{"#attributes":{"Code":"SGL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}},{"#attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}}]';
var priceModal2 = '[{"#attributes":{"Code":"SGL","Total":"225000"},"DayPrice":{"Date":"2016-05-26","Rate":"225000"}},{"#attributes":{"Code":"DBL","Total":"225000"},"DayPrice":{"Date":"2016-05-26","Rate":"225000"}}]';
var priceModal3 = '[{"#attributes":{"Code":"SGL","Total":"410000"},"DayPrice":{"Date":"2016-05-26","Rate":"410000"}},{"#attributes":{"Code":"DBL","Total":"410000"},"DayPrice":{"Date":"2016-05-26","Rate":"410000"}}]';
var isitable = '';
isitable += '<br><button class="btn blue tes_button" data-toggle="modal" data-target="#priceModal" id="priceModel1" data-json='+priceModal1+'>Test get parameter json array 1</button><br><br>';
isitable += '<button class="btn blue tes_button" data-toggle="modal" data-target="#priceModal" id="priceModel2" data-json='+priceModal2+'>Test get parameter json array 2</button><br><br>';
isitable += '<button class="btn blue tes_button" data-toggle="modal" data-target="#priceModal" id="priceModel3" data-json='+priceModal3+'>Test get parameter json array 3</button><br>';
console.log(isitable);
$("#tes").html(isitable);
}
});
});
$('#priceModal').on('show.bs.modal', function(e) {
//console.log('yes');
var json = $(this).attr("data-json");
$(".modal-body").html(json);
console.log("JSON »» From priceModel Element "+json);
console.log(JSON.parse(json));
})
});
When click button "Click me", It will display three button. Look jsfidde.
When click button "Test get parameter json array 1", I want send parameter priceModal1 to modal.
When click button "Test get parameter json array 2", I want send parameter priceModal2 to modal
When click button "Test get parameter json array 3", I want send parameter priceModal3 to modal
Parameter priceModal1, priceModal2 and priceModal3 contain json array. I do
console.log("JSON »» From priceModel Element "+json);
console.log(JSON.parse(json));
in $('#priceModal').on('show.bs.modal', function(e) {.
But it's not working.
Although I using : $(this).attr("data-json");
Any solution to solve my problem?
Thank you
this inside the show.bs.modal event, refers to the modal itself, while the json data attribute is set at the button. You can access the button that triggered the event at e.relatedTarget.
var json = $(e.relatedTarget).attr('data-json');
Furthermore, accessing a data- attribute with $.data will automatically parse JSON. So you could instead write:
var json = $(e.relatedTarget).data('json');
... and skip JSON.parse, as json is now an object and not a string.