in my project I'm Working with Asp core 3.1, I'm saving data with ajax using bootstrap modal and it saves but modal didn't hide in success and I want to show another modal with data feedback it didn't show either it shows dialog with html markup like in picture
so here is my ajax Code
$('#btnSave').click(function (event) {
event.preventDefault();
Add();
});
function Add() {
var res = Validate();
if (res == false) {
return false;
}
var CategoryObj = {
CategoryName: $("#inputCategory").val()
};
$.ajax({
url: "/Writer/SaveCategory",
data: JSON.stringify(CategoryObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
$('#NewCategory').modal('hide');
$("#content").html(result);
$("#ResultCategory").modal("show");
$("#ResultCategory").appendTo("body");;
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
and in my controller code
[HttpPost]
public async Task<IActionResult> SaveCategory([FromBody]CategoryModelDto categoryModel)
{
CategoryModelDto categoryModelDto = new CategoryModelDto();
if (ModelState.IsValid==true)
{
categoryModelDto= await _categoryService.CreateNewCategory(categoryModel);
}
return PartialView("_CategoryResult", categoryModelDto);
}
and my view
<button type="button" id="addCategory" style="margin-left:15px;" class="btn btn-primary">
New Category
<div class="modal fade" id="NewCategory" tabindex="-1" role="dialog" aria-labelledby="NewCategoryLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div id="modalContent" class="modal-content">
<partial name="_CreateCategory" model="Model.CategoryModel" />
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<div class="modal fade" id="ResultCategory" tabindex="-1" role="dialog" aria-labelledby="ResultCategoryLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div id="content" class="modal-content">
<partial name="_CategoryResult" model="Model.CategoryModel" />
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
So I need help to get hide the save modal and show another modal with return data
I solve the problem actually the problem was in one line in ajax code So all the code in controller and the view is correct and the line data type must be deleted the line is
dataType: "json"
When I deleted this line the code is working Well Thanks for every one
If you want to close NewCategory modal and replace partial view of ResultCategory modal when click button which id is btnSave,try to use the following code:
ResultCategory modal:
<div class="modal fade" id="ResultCategory" tabindex="-1" role="dialog" aria-labelledby="ResultCategoryLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<partial name="_CategoryResult" model="Model.CategoryModel" />
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
js:
$('#btnSave').click(function (event) {
event.preventDefault();
$('#NewCategory').modal('hide');
Add();
});
function Add() {
var res = Validate();
if (res == false) {
return false;
}
var CategoryObj = {
CategoryName: $("#inputCategory").val()
};
$.ajax({
url: "/Writer/SaveCategory",
data: JSON.stringify(CategoryObj),
type: "POST",
contentType: "application/json;charset=utf-8",
success: function (result) {
document.getElementById("content").innerHTML = result;
$("#ResultCategory").modal("show");
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
Related
I have a simple form that shows a modal popup upon ajax success. It works great the 2nd time its used in same session. The modal will never show on the first form submission. What could be causing the modal not to fire the first time around? Maybe the page refresh or form reset?
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
$("#submitbtn").prop('disabled', true);
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
$("#output").fadeTo(4000, 500).slideUp(500, function(){
$("#output").slideUp(500);
});
$("#myform")[0].reset();
$("#submitbtn").prop('disabled', false);
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000)
});
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#myform').validator();
// when the form is submitted
$('#myform').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "add_report.php";
var formData = new FormData($('#myform')[0]);
$.ajax({
url: 'add_report_do.php',
enctype: 'multipart/form-data',
type: 'POST',
data: formData,
success: function(response) {$("#successModal").modal("show");},
contentType: false,
processData: false,
cache: false
});
return false;
}
})
});
<div id="successModal" class="modal modal-blur fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<p>Fishing report successfully added.<br /></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn- btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
Well I figured it out. require.js and jquery were stepping on each other. Added a line to require.config to isolate jquery. Works fine now
define('jquery', function () { return jQuery; });
I have tried to solve this problem several hours but I never solve this problem
I have a problem with my code, when I click the delete button from json, I can't get the ID just link from the console like this:
example :
That happened : request
I want Like this : request/?id=1
I paste some code to check :
Controller request.php:
public function delete()
{
// $this->m_request->delete($this->input->post('id_form'));
$id = $this->input->post('id_form');
$data = $this->m_request->DeleteRequest($id);
echo json_encode($data);
}
Model m_request.php:
public function DeleteRequest($id)
{
$hasil = $this->db->query("DELETE FROM request WHERE id_form='$id'");
return $hasil;
}
And Then View (I just put the modal script and ajax json script) :
Modal View :
<div class="modal fade" id="ModalHapus" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Hapus Request</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button>
</div>
<form class="form-horizontal">
<div class="modal-body">
<input type="hidden" name="kode" id="textkode" value="">
<div class="alert alert-warning">
<p>Apakah Anda yakin mau menghapus request ini?</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
<button class="btn_hapus btn btn-danger" id="btn_hapus">Hapus</button>
</div>
</form>
</div>
</div>
Ajax/JSON Script :
//GET HAPUS
$(document).on('click', '.hapus', function() {
var id = $(this).attr('data');
$('#ModalHapus').modal('show');
$('[name="kode"]').val(id);
})
// Hapus Request
$('#btn_hapus').on('click',function(e){
e.preventDefault();
var id = $('textkode').val();
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: {id:id},
success: function(data){
// $('#ModalHapus').modal('hide');
console.log(data)
load_data();
}
});
return false;
})
There are a lot of reasons why the ajax request is possibly not working. The first thing which came in my mind is, that you have not specified an ID and method of the input form. Make sure you have both in your HTML form tag. For example:
<form id=“id_form” method=“post” class=“...”>
...
<input type="text" name="kode" id="textkode">
</form>
In you JS Code do the following
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: $(“#id_form”).serialize(),
success: function(data){
console.log(data)
load_data();
}
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nERROR: "+ err);
}
});
Also change the your delete function to this:
public function deleteTableRow()
{
$id = $_POST['textkode']; // Because I'm not sure what this->input->post() makes
$result = $this->m_request->DeleteRequest($id);
echo json_encode(array('id' => $id, 'result' => $result)); // The contents of array should then be displayed in the console of your webbrowser
}
Note that I changed the function name. It could be very misleading for other programmers, because delete is used in many programming languages as destructor for dynamic objects!
Additionally I would recommend to create an ajax.php file to parse different kind of ajax request. This file would also work as a controller, but just for ajax calls. In case you have several forms, the code is more readable.
I'm trying to send a form content to current(or another) php file for processing, but I don't know how be sure that my codes works!
<a href="#" class="eb" date-uid="<?php echo $value[0]; ?>" data-toggle="modal" data-target=".bs-example-modal-lg">
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<H2>Edit contact</H2>
<form name="editform" method="post">
<input type="name" name="ename" placeholder="name" required /></br></br>
<input type="tel" name="etel" placeholder="phone number" required /></br></br>
<input type="text" name="edes" placeholder="description" required /></br></br>
<input type="submit" class="esub" name="esub" value="Save" />
</form>
<script>
$(document).ready(
function () {
$(".esub").click(
function () {
var uid = $(".eb").attr("data-id");
var ename = document.getElementByName("ename");
var etel = document.getElementByName("etel");
var edes = document.getElementByName("edes");
ajax({
url: 'uedit.php',
type: 'POST',
data: {
owner: uid,
name: ename,
tel: etel,
description: edes
},
success: function (result) {
return result;
}
});
}
);
}
);
</script>
So is my code right? How could I be sure that my codes run correctly?
remove this line from your jquery code
var uid=$(".eb").attr("data-id");
becouse there is no element having class="eb"
You have a couple errors in your code. Try this:
<script>
$( document ).ready(function() {
$(".esub").click(function(){
var uid=$(".eb").attr("data-id");
var ename=getElementByName("ename");
var etel=getElementByName("etel");
var edes=getElementByName("edes");
ajax({
url:'uedit.php',
type:'POST',
data:({
owner:uid,
name:ename,
tel:etel,
description:edes
}),
success:function(result){
return result;
}
});
});
});
</script>
I'd like to display a confirm delete dialog using Bootstrap v3 before deleting an entity.
My code works fine, but without confirm dialog. How can I do that?
{% for travel in pagination %}
<div class="col-sm-6 col-md-4" id="item-{{ travel.id }}">
//......
<a title="delete" href data-entity-id="{{ travel.id }}" class="button btn-mini red remove_item">Delete</a>
</div>
{% endfor %}
<script>
$(document).ready(function () {
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('travel_delete', {'id': entityId}),
success: function () {
//hide the block of item after delete success
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>
Edited
I tried this code. I'd like when clicking on delete link, pass the value of attr entity-id which is in the delete link, to the attr data-entity-id in delete button in the modal. How can I do that ?
error console:
Failed to load resource: the server responded with a status of 404 (Not Found)
<a title="delete" href data-toggle="modal" data-target="#myModal" entity-id="{{ travel.id }}" class="button btn-mini uppercase red">Sup ajax</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button data-entity-id="" type="button" class="btn btn-primary remove_item">Delete</button>
</div>
<script>
$(document).ready(function () {
$('#myModal').on('show.bs.modal', function () {
var entityId = $(this).attr('entity-id');
// set new value of attr data-entity-id but doesn't work
$('.remove_item').attr('data-entity-id', entityId);
});
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('frontend_travel_delete_favorite', {'id': entityId}),
success: function () {
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>
Try to do this:
<a id="delete-btn" title="delete" href data-toggle="modal" data-target="#myModal" data-entity-id="{{ travel.id }}" class="button btn-mini uppercase red">Sup ajax</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button data-entity-id="" type="button" class="btn btn-primary remove_item">Delete</button>
</div>
<script>
$(document).ready(function () {
$('#delete-btn').on('click', function () {
var entityId = $(this).attr('data-entity-id');
$('.remove_item').attr('data-entity-id', entityId);
});
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('frontend_travel_delete_favorite', {'id': entityId}),
success: function () {
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>
I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});