ajax stop bootstrap modal box from closing when user clicks submit - javascript

This is a bit of a tricky problem to explain but here goes:
I would like to display results inside a bootstrap modalbox, doing the following:
Selectbox1-->populates-->SelectBox2-->populates-->Selectbox3
Get values from selectboxes when user clicks submit
Query database with selectbox values
Display result in modal box
My problem
Everything is working however when user clicks submit the modalbox closes, when I open the modalbox again the result is inside the modalbox
HOW CAN I GET THE MODALBOX TO NOT CLOSE WHEN USER CLICKS SUBMIT?
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<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">
<script type="text/javascript">
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'functionTest.php',
data: formData,
type: 'post',
success: function(data) {
$('#resultForm').replaceWith(data);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
</head>
<body>
<center>
<div>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
include('connect.php');
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
if(isset($_POST['submit'])){
echo $tour = $_POST['tournament'];
echo $round = $_POST['round'];
}

It seems that you're missing a "return false;" in your form submit event handler:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'functionTest.php',
data: formData,
type: 'post',
success: function(data) {
$('#resultForm').replaceWith(data);
}
});
//Return false to cancel submit
return false;
});

Try to remove the class close from the button

I haven't tested your solution, but try putting e.stopPropagation(); before e.preventDefault();
UPDATE
Why is your Modal in the <head> part ?

Related

form validation codeigniter 3 with ajax always false when update data

hi guys i have problem when update my data using codeigniter and ajax, when update data my form validation always return false.. but when insert data thats work normal. this is my code, i hope someone can help me, thx a lot..
my controller
public function updateFakultas()
{
$id = $this->input->post('id', true);
$fakultas = $this->input->post('fakultas', true);
$this->form_validation->set_rules('fakul', 'Fakultas', 'required');
if ($this->form_validation->run() == FALSE) {
$hasil = [
'error' => true,
'fakultas' => form_error('fakul', '<p class="mt-3 text-danger">', '</p>'),
];
echo json_encode($hasil);
} else {
$this->Fakultas_model->updateData($id, $fakultas);
$hasil = [
'error' => false
];
echo json_encode($hasil);
}
}
ajax
$('#data_fakultas').on('click', '.item_edit', function() {
var id = $(this).attr('data');
$('#id_fakultas').val("");
$('#fakultas2').val("");
$('#fakultas_error2').html("");
$.ajax({
type: 'POST',
url: '<?= base_url() ?>fakultas/getFakultas',
data: {
id: id
},
dataType: 'json',
success: function(data) {
$('#ModalUbahFakultas').modal('show');
$('[name="id"]').val(data[0].id_fakultas);
$('[name="fakul"]').val(data[0].nama_fakultas);
}
})
})
$('#ubah-fakultas').on('click', function() {
var id = $('#id_fakultas').val();
var fakultas = $('#fakultas2').val();
$.ajax({
type: 'post',
url: '<?= base_url() ?>fakultas/updateFakultas',
data: {
id: id,
fakultas: fakultas
},
dataType: 'json',
success: function(data) {
console.log(data);
if (data.error == false) {
$('#ModalUbahFakultas').modal('hide');
swal("Good Job!", "Data berhasil diubah", "success");
$('#fakultas_error2').html("");
$('#fakultas2').val("");
tampil_data_fakultas();
} else {
$('#fakultas_error2').html(data.fakultas);
$('#fakultas2').on('keyup', function() {
$('#fakultas_error2').html("");
})
}
}
})
})
my view
<div class="modal fade" id="ModalUbahFakultas" tabindex="-1" role="dialog" aria-labelledby="UbahLabelFakultas" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="UbahLabelFakultas">Form Ubah Fakultas</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="id_fakultas" name="id">
<div class="form-group">
<label for="fakultas2">Nama Fakultas</label>
<input type="text" class="form-control" id="fakultas2" name="fakul">
<div id="fakultas_error2"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
<button type="submit" class="btn btn-primary" id="ubah-fakultas">Update Data</button>
</div>
</div>
</div>
</div>
i already try to console when ajax post, its fine but i think this problem with form_validation->run()..
you are making a silly mistake while setting validation rule.
your code
$this->form_validation->set_rules('fakul', 'Fakultas', 'required');
Change to
$this->form_validation->set_rules('fakultas', 'Fakultas', 'required');
Your mistaking post variable name "fakultas" with "fakul" while making an Ajax post.
Check your Javascript code
$.ajax({
type: 'post',
url: '<?= base_url() ?>fakultas/updateFakultas',
data: {
id: id,
fakultas: fakultas
},
dataType: 'json',
success: function(data) {
console.log(data);
if (data.error == false) {
$('#ModalUbahFakultas').modal('hide');
swal("Good Job!", "Data berhasil diubah", "success");
$('#fakultas_error2').html("");
$('#fakultas2').val("");
tampil_data_fakultas();
} else {
$('#fakultas_error2').html(data.fakultas);
$('#fakultas2').on('keyup', function() {
$('#fakultas_error2').html("");
})
}
}
})

Codeigniter & AJAX - Reset/clear the modal form when close the edit modal

I have a problem on my modal form when I open the edit modal ,the modal pop up and it fetched my data and that is WORKING WELL but when I close the modal and click the add new user, the data is automatically fetched why is it fetched when I close the modal it should be reset to blank?
how can I reset or clear my form modal after i close the modal and not doing anything?
here is my Edit Javascript/Ajax code
$('#btnClose').click(function(){
$('#myForm')[0].reset();
}); //I Tried this block of code, but it didnt work
//Edit/Show
$('#showdata').on('click','.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Employee');
$('#myForm').attr('action', '<?php echo base_url() ?>employees/updateEmployee');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>employees/editEmployee',
data: {id:id},
async: false,
dataType:'json',
success: function(data){
$('input[name=txtEmployeeName]').val(data.employee_name);
$('textarea[name=txtAddress]').val(data.address);
$('input[name=txtId]').val(data.id);
},
error: function(){
aler('Could not edit Data');
}
});
});
and here is my modal (I use this modal to create and edit my data so it is just a one modal)
<!--MODAL-->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal">
<input type="hidden" name="txtId" value="0">
<div class="form-group">
<label for="name" class="label-control col-md-4">Employee Name</label>
<div class="col-md-8">
<input type="text" name="txtEmployeeName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="address" class="label-control col-md-4">Address</label>
<div class="col-md-8">
<textarea class="form-control" name="txtAddress"></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!--END MODAL-->
IN CASE you need to see my add/create javascript code here it is
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//form validation
var employeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (employeeName.val() == '') {
employeeName.parent().parent().addClass('has-error');
}else{
employeeName.parent().parent().removeClass('has-error');
formValid = false;
}
if (address.val()=='') {
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
formValid = false;
}
if (!formValid) {
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if (response.success) {
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if (response.type=='add') {
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(3000).fadeOut('slow');
showAllEmployees();
}else{
alert('Error');
}
},
error: function(){
alert('Data is not added');
}
});
}
});
Replace
$('#btnClose').click(function(){
$('#myForm')[0].reset();
});
with the following code,
$("#myModal").on("hidden.bs.modal", function () {
$('#myForm')[0].reset();
});

How to insert data from a modal PHP Codeigniter

I have a modal form (simple) that I want to insert in my BD, but I'm not getting the expected result
modalview
this is the button that calls my modal:
<button type='button' class='btn btn-info' data-toggle="modal" data-target="#modal-default-cliente"><span class='fa fa-plus'></span></button>
this is my modal:
<div class="modal fade" id="modal-default-cliente">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Agregar Usuario</h4>
</div>
<div class="modal-body">
<form method="POST" id="clienteform">
<div class="form-group">
<label for="nombrecompleto">Nombre Completo:</label>
<input type="text" class="form-control" name="nombremodal" id="nombremodal" required="required">
</div>
<div class="form-group">
<label for="telefono">Teléfono:</label>
<input type="text" class="form-control" name="telefonomodal" id="telefonomodal">
</div>
<div class="form-group">
<label for="direccion">Dirección:</label>
<input type="text" class="form-control" name="direccionmodal" id="direccionmodal">
</div>
<div class="form-group">
<input type="submit" name="action" class="btn btn-success" value="Guardar">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
This is my Javascript code, which by the way the parameters of the form arrive
$(document).on("submit", "#clienteform", function(event){
event.preventDefault();
var nombre = $("#nombremodal").val();
var telefono = $("#telefonomodal").val();
var direccion = $("#direccionmodal").val();
$.ajax({
url: base_url+"mantenimiento/Ventas/agregarClientemodal",
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
This is my action in the "Ventas" Controller:
public function agregarClientemodal(){
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
}
and finally my function in the Sales model:
public function agregarUsuariomodal($data){
return $this->db->insert("Clientes",$data);
}
I'm new to Codeigniter, and when I click on my save button, my modal window does nothing
Expected behavior: save the record and hide the modal
behavior obtained: clicking on the submit does nothing
what am I doing wrong? What do I need to validate? any help for me?
Hope this will help you :
Pass form post values with ajax's data using var formdata = $(this).serialize();, and use site_url() for the URL
Your ajax should be like this :
$(document).ready(function(){
$("#clienteform").on("submit", function(event){
event.preventDefault();
var formdata = $(this).serialize();
$.ajax({
url: '<?=site_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
data : formdata,
success: function(data)
{
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
});
Your agregarClientemodal method should be like this :
public function agregarClientemodal()
{
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
echo "success";
exit;
}
Your base_url variable is not defined in javascript/jquery.
So you need to change that line into:
$.ajax({
url: '<?php echo base_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
it will generate correct url.
Further you can check console for error logs.

Show error in modal window, when something went wrong

I need some help. I need to show up the error, when something went wrong in my modal window. Right now, is just closing, also when there are error. I tried to find some Ajax and Javascript to solve the problem, but I can’t get it to work well. Can someone help me and thanks for your help?
if($result->num_rows == 0) {
$this->errors[] = "User not fund";
}else{
Modal window
<!-- Modal -->
<div class="modal fade" id="resetPassword" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div style="background-color:#3a3a38;" class="modal-content">
<div class="modal-header">
<h4 style="color:#fff" class="modal-title">Nulstill adgangskode</h4>
</div>
<div class="modal-body">
<form role="form" action="index.php" method="post">
<div class="form-group">
<label class="sr-only"
for="email_forgot">Email</label>
<input type="text" name="email_forgot"
placeholder="email..." class="form-username form-control" id="form-username">
</div>
<input style="margin-left:auto;margin-
right:auto;" data-backdrop="static" data-keyboard="false" class="btn-lg btn-
default btn-block" type="submit" value="send" name="forgot">
</form>
<?php
if (isset($user)) {
if ($user->errors) {
foreach ($user->errors as $error) {
echo '<a style="color:red">'.$error.'</a>';
}
}
if ($user->messages) {
foreach ($user->messages as $message) {
echo '<span style="color:red">'. $message.'</span>';
}
}
}
?>
</div>
</div>
</div>
Submit the form with ajax and display the error with javascript not with php. Now your page reload and you loss the data.
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
$('form').on('submit', function(event){
event.preventDefault();
var formData = $("form").serializeArray();
$.ajax({
url: "index.php",
type: "POST",
data: formData,
dataType: 'json',
success:function(data){
$('body').html('<h1>Thank You</h1>');
},
error:function(){
$('body').html('<h1>Error</h1>');
}
});
});
There are two different options when it comes down to posting your data; you could ajax-validate the data (which means that you'd validate the content in a different file), or you'd ajax-submit the data (which means that you'd validate and use the data in a different file).
I'd suggest ajax-submitting, seeing as that would suit te needs of your form.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var $form = $('#resetPassword form');
$form.submit(function(event) {
event.preventDefault();
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function ( response ) {
if(response != "") {
alert("Errors: " + response);
} else {
alert("Password reset!");
}
}
});
});
</script>
For it to work you'd have to use the METHOD attribute on the form to point to a processing file, which you'll have to create (for example; ajax-reset-password.php). In there just print all errors, if there are any. If no errors occurred, just don't print anything. The javascript above will show the message "Password reset!".

Undefined Index error (Codeigniter)

My code was working fine before. But Now it is not working. I am working on codeigniter and I am uploading a file using jquery ajax. I donot know why my code stop working. If you can find the issue please let me know.
Here is the controller code
public function updatedp()
{
$var = $_FILES['fileUp'];
$img=$_FILES['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
} else {
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
My jquery code which calling above function:
$("#btnupdate").click(function(event){
if($("#fileupload2").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
return $.ajaxSettings.xhr();
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
});
}
});
event.preventDefault();
}
} else {
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
});
}
});
HTML:
<div class="modal fade" id="myModal" role="dialog">
<form enctype="multipart/form-data" name="formname" id="formname" method="post" action="">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header ">
<script type="text/javascript">
$(document).ready(function(){
$('#mgupload-dp').click(function(e){
$('#fileupload2').click();
e.preventDefault();
});
});
</script>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create profile picture</h4>
</div>
<div class="modal-body">
<div class="text-center" style="width:100%"> <img src="<?php echo base_url(); ?>img/profile.png" alt="add dp" id="pop-dp" >
<button type="button" class="btn btn-default text-center" id="mgupload-dp">Choose picture to upload</button>
<input type="file" id="fileupload2" name="fileUp" class="hidden-dp" accept="image/*">
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnupdate">Update Picture</button>
</div>
</div>
</div>
</div>
</form>
</div>
Files are not uploading and I am getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: fileUp
Filename: controllers/Userpage.php
Open the Firebug in FF.
Click on the ajax call URL under Console.
See what are passed under "Post" tab.
If fileUp is present there, use $this->input->post('fileUp'); to fetch the contents.

Categories