I want to my grant my Admin the priviledges to add and edit user. Clicking the Add button pops up a modal which os userModal and its working perfectly - I send a request to user_action.php (where my PHP and SQL statements are) and it creates a new user.
When the Admin clicks on the Update button, i want the userModal to pop up again, but this time, populated with the username, email and usertype of the user that is to be edited (The modal-title changes from Add User to Edit User and the btn-action changes to 'Edit`). This is not working - the modal doesn't show.
What is the problem?
I have attached the html to my users.php and the jQuery. I have also attached the screenshot of the UI of users.php in case it can be of help.
HTML
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("./database/dbnew.php");
if($_SESSION['usertype'] != 'Admin')
{
header("location:index.php");
}
include("./templates/header.php");
?>
<span id="alert_action"></span>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-6">
<h3 class="panel-title">User List</h3>
</div>
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" align="right">
<button type="button" name="add" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success btn-xs">Add</button>
</div>
</div>
<div class="clear:both"></div>
</div>
<div class="panel-body">
<div class="row"><div class="col-sm-12 table-responsive">
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Email</th>
<th>Name</th>
<th>Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter User Name</label>
<input type="text" name="username" id="username" class="form-control" required />
</div>
<div class="form-group">
<label>Enter User Email</label>
<input type="email" name="email" id="email" class="form-control" required />
</div>
<div class="form-group">
<label>Enter User Password</label>
<input type="password" name="password" id="password" class="form-control" required />
</div>
<div class="form-group">
<label for="usertype">Usertype</label>
<select name="usertype" class="form-control" name="usertype" id="usertype" required>
<option value="">Choose User Type</option>
<option value="Admin">Admin</option>
<option value="Other">Other</option>
</select>
<small id="t_error" class="form-text text-muted"></small>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="id" id="id" />
<input type="hidden" name="btn_action" id="btn_action" />
<input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
jQuery
<script>
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').html("<i class='fa fa-plus'></i> Add User");
$('#action').val("Add");
$('#btn_action').val("Add");
});
var userdataTable = $('#user_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax":{
url:"user_fetch.php",
type:"POST"
},
"columnDefs":[
{
"target":[4,5],
"orderable":false
}
],
"pageLength": 25
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
$('#action').attr('disabled','disabled');
var form_data = $(this).serialize();
$.ajax({
url:"user_action.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#user_form')[0].reset();
$('#userModal').modal('hide');
$('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
$('#action').attr('disabled', false);
userdataTable.ajax.reload();
}
})
});
$(document).on('click', '.update', function(){
var id = $(this).attr("id");//user_id
var btn_action = 'fetch_single';
$.ajax({
url:"user_action.php",
method:"POST",
data:{id:id, btn_action:btn_action},//user_id
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#username').val(data.username);
$('#email').val(data.email);
$('#usertype').val(data.usertype);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit User");
$('#id').val(id);//user_id
$('#action').val('Edit');
$('#btn_action').val('Edit');
$('#password').attr('required', false);
$('#usertype').attr('required', false);
}
})
});
});
</script>
Screenshot
users.php UI
Any form of assistance will be appreciated.
Related
I have a table that will retrieve all the users information along with a button that will open a popup modal to edit the user details. The Modal will display the user data correctly , but when I try to save the changes that the user has entered on a button click, the value of the textboxes will be the first row of the table bot the one that the user entered. How can I get the value of the textbox that is currently displayed on the modal popup.
My View:
<div class="form-group" align="center">
<table id="AllUsersTable2" class="display" style="width:100%;">
<tr>
<th>id</th>
<th>FullName</th>
<th>username</th>
<th>MobileNumber</th>
<th>Email</th>
<th>IsActiveText</th>
<th>RoleName</th>
<th>Edit</th>
</tr>
#foreach (var user in Model.UserTable)
{
<tr>
<td>#user.NationalID</td>
<td>#user.FullName</td>
<td>#user.username</td>
<td>#user.MobileNumber</td>
<td>#user.Email</td>
<td>#user.IsActiveText</td>
<td>#user.RoleName</td>
<td><button class="btn btn-primary" id="" data-toggle="modal" data-target="##user.NationalID">عرض</button></td>
</tr>
//PopUp Starts HERE
<div class="modal fade" id="#user.NationalID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title" id="test2" style="text-align: right;"> بيانات المستخدم</h1>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
#using (Html.BeginForm(Html.BeginForm(null, null, FormMethod.Post, new { #id = "UpdateUserForm" })))
{
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="NationalID" class="control-label">رقم الهوية</label>
<input type="text" id="UpdateuNationalID" name="NationalID" value="#user.NationalID" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="FullName" class="control-label">الإسم</label>
<input type="text" id="UpdateFullName" name="FullName" value="#user.FullName" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="username" class="control-label">اسم المستخدم</label>
<input type="text" id="Updateusername" name="username" value="#user.username" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="MobileNumber" class="control-label">رقم الهاتف</label>
<input type="text" id="UpdateMobileNumber" name="MobileNumber" value="#user.MobileNumber" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Email" class="control-label">البريد الإلكتروني</label>
<input type="text" id="UpdateEmail" name="Email" value="#user.Email" class="control-label">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="IsActive" class="control-label">حالة المستدم</label>
<select name="IsActive" id="UpdateIsActive">
<option value="">...</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="RoleId" class="control-label">البريد الإلكتروني</label>
<select name="RoleId" id="UpdateRoleId">
<option value="">...</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
</div>
</div>
</div>
</div>
}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn">تعديل المستخدم </button>
</div>
</div>
</div>
</div>
//PopUp END HERE
}
</table>
</div>
My Click Event:
$('body').on('click', '.UpdateUserBtn', function (e) {
var NationalID = $("#UpdateuNationalID").val();
console.log(NationalID);
var username = $('#Updateusername').val();
var FullName = $('#UpdateFullName').val();
var MobileNumber = $('#UpdateMobileNumber').val();
var Email = $('#UpdateEmail').val();
var RoleId = $('#UpdateRoleId').val();
var IsActive = $('#UpdateIsActive').val();
$.post("#Url.Action("UpdateUser", "Home")", { NationalID: NationalID, username: username, FullName: FullName, MobileNumber: MobileNumber, Email: Email, RoleId: RoleId, IsActive: IsActive }, function (data) {
if (data.Result == 1) {
//closePopup();
$.notify(
"تم الحفظ بنجاح",
{
globalPosition: 'top center',
className: 'success'
}
);
}
else {
console.log(data);
$.notify(
"حدث خطأ أثناء الحفظ ",
{
globalPosition: 'top center',
className: 'danger'
}
);
// console.log(data);
}
});
});
The problem here for example the value of $("#UpdateuNationalID").val(); will be always the value of first row of the table not the value that is displayed on the popup..
The problem as said by #Carsten Løvbo Andersenis is that you are using the same Id when generating the HTML, so your jQuery var NationalID = $("#UpdateuNationalID").val(); will take the first value that he find.
To solve this, you need to assign a different Id in every loop, for example you can do ad follow if we suppose that NationalID is unique :
<input type="text" id='UpdateuNationalID #user.NationalID' name="NationalID" value="#user.NationalID" class="control-label" required>
EDIT:
You have to create a function for example SaveMe instead to wait for the event click, and you need to send a value on click in your modal:
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn" onclick="SaveMe(#user.NationalID)">تعديل المستخدم </button>
and your event listner first line $('body').on('click', '.UpdateUserBtn', function (e) {
change it to be a function:
function SaveMe(myId) {
var str1 = 'UpdateuNationalID ' + myId;
var NationalID = document.getElementById(str1).innerHTML;
// or
var NationalID = document.getElementById(str1).value;
// then
console.log(NationalID);
*I am beginner so spare me. I am using code igniter. I have a table and in this table I have a button edit. When the edit button is clicked it shows a pop up modal. Main purpose of this is to update the specific row data like name password etc. That why i called modal pop up which displays a form where i want to show specific record so that i can edit that record and click update which will update the record. I just want to show the specific record as each row have its own edit button. i can change the record through php. but need to display it.
This is my modal popup and that table where the data from database is displayed.
Someone please tell what is the code to do this work. I want full ajax code so anyone who have a kind heart please write that code so that i can enter into my website. Please help. this is all i know and i have shared
Code:
<div class="modal fade bs-example-modal-lg" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel2">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel1">Update Current User</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="card">
<div class="card-header">
End User Info
</div>
<div class="card-body">
<form action="<?php echo base_url()."User_area/add_new_subusers"?>" method="post" id="newuserform" class="form-horizontal">
<div class="form-body">
<div class="row">
<div class="col-md-12">
<div class="form-group row">
<label class="control-label text-right col-md-5">First Name:</label>
<div class="col-md-7">
<input type="text" class="form-control" id="subufname" value="" name="subufname" placeholder="Enter First Name"></input>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group row">
<label class="control-label text-right col-md-5">Last Name:</label>
<div class="col-md-7">
<input type="text" class="form-control" name="subulname" id="subulname" value="" placeholder="Enter Last Name"></input>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group row">
<label class="control-label text-right col-md-5">Email:</label>
<div class="col-md-7">
<input type="text" class="form-control" id="subuemail" name="subuemail" value="" placeholder="Enter Email"></input>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-12">
<div class="form-group row">
<label class="control-label text-right col-md-5">Password:</label>
<div class="col-md-7">
<input type="text" class="form-control" name="subupass" id="subupass" placeholder="New Password"></input>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-12">
<div class="form-group row">
<label class="control-label text-right col-md-5">Confirm Password:</label>
<div class="col-md-7">
<input type="text" class="form-control" id="subuconfirmpass" placeholder="Confirm New Password"></input>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" id="createnewuser" value="Update" class="btn btn-primary">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div></div>
<div class="card">
<div class="card-header">
</div>
<div class="card-body">
<div class="table-responsive m-t-40">
<table id="myTable" class="table table-bordered table-striped">
<thead style="background: #37a000; color: #fff;">
<tr>
<th>Name</th>
<th>Email/Username</th>
<th>Password</th>
<th>User Role</th>
<th>Email Notification</th>
<th>Client Access</th>
<th>Action</th>
</tr>
</thead>
<!-- ******************************Displaying Data*************************************************************** -->
<tbody>
<?php
foreach($profle as $row): ?>
<tr>
<td><?echo $row['fname']?></td>
<td><?echo $row['email']?></td>
<td><?echo $row['password']?></td>
<td><?echo $row['user_role']?></td>
<td>***</td>
<td>***</td>
<td><a class="btn btn-success" style="color:white;background-color:green;padding:0px 2px;" data-toggle="modal" data-target="#exampleModal2">edit</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
Simple ajax for you . Hope it can help you
ajax script:
<script>
$(document).ready(function(){
$("#popup-button").click(function(event){
event.preventDefault();
var profle_id =$(this).children().val();
$.ajax({
url: "HERE FILE CONTROLLER",
type : 'get',
data: "id="+profle_id,
dataType : 'json',
success: function(result){ // result ='{ "fname":"John", "email":"abc#gmail", "password":"New York" , "user_role":"York" }';
$('#subufname').val(result['name']);
$('#subulname').val(result['email']);
$('#subuemail').val(result['password']);
$('#subupass').val(result['user_role']);
}
});
});
});
</script>
edit table :
<tr>
<td><?echo $row['fname']?></td>
<td><?echo $row['email']?></td>
<td><?echo $row['password']?></td>
<td><?echo $row['user_role']?></td>
<td>***</td>
<td>***</td>
<td><a class="btn btn-success" style="color:white;background-color:green;padding:0px 2px;" data-toggle="modal" data-target="#exampleModal2" id = "popup-button">edit<input type="hidden" value ="$row['id']" ></a></td>
</tr>
I currently have the following datatable to display my list of contacts from the database. Each row, I have also insert a "Edit" & "Delete" button and have the data-id="<?=$row['id']?>" passed for the jQuery to handle when the button is clicked. When the button is clicked, through ajax, I will get the data from getcontact.php and set it to the respective input in the modal form, however the data does not seem to be displaying in the form values. May I know where did I go wrong?
tables.php
<table width="100%" class="display table table-striped table-bordered table-hover" id="contactsTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Company</th>
<th>Position</th>
<th>Phone</th>
<th>Email</th>
<th>Gender</th>
<th>Date Registered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['company']?></td>
<td><?=$row['position']?></td>
<td><?=$row['phone']?></td>
<td><?=$row['email']?></td>
<td><?=$row['gender']?></td>
<td><?=$row['dateregistered']?></td>
<td>
<!-- Edit Button trigger modal -->
<button id="editButton" type="button" class="btn btn-primary" datatoggle="modal" data-target="#editModal" data-id="<?=$row['id']?>">
Edit
</button>
</td>
<td>
<!-- Delete Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal" data-id="<?=$row['id']?>">
Delete
</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
Modal (in the same page as tables.php)
<!-- Edit Contact Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria labelledby="myModalLabel">
<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" id="myModalLabel">Edit Contact</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" method="POST" id="editForm" role="form">
<div class="form-group animated fadeIn">
<label for="nameInput" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="name" name="name" class="form-control" id="nameInput" placeholder="Name" required>
</div>
</div>
<div class="form-group animated fadeIn">
<label for="companyInput" class="col-sm-2 control-label">Company</label>
<div class="col-sm-10">
<input type="company" name="company" class="form-control" id="companyInput" placeholder="Company" required>
</div>
</div>
<div class="form-group animated fadeIn">
<label for="posInput" class="col-sm-2 control-label">Position</label>
<div class="col-sm-10">
<input type="position" name="position" class="form-control" id="posInput" placeholder="Position/Job Title">
</div>
</div>
<div class="form-group animated fadeIn">
<label for="contactInput" class="col-sm-2 control-label">Contact Number</label>
<div class="col-sm-10">
<input type="number" name="contact" class="form-control" id="contactInput" placeholder="Office/Mobile Number" data-error="Please enter a valid mobile number" required>
</div>
</div>
<div class="form-group animated fadeIn">
<label for="emailInput" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" id="emailInput" placeholder="Email Address">
</div>
</div>
<div class="form-group animated fadeIn">
<label for="genderInput" class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<input type="gender" name="gender" class="form-control" id="genderInput" placeholder="Male/Female">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="editContact" type="button" class="btn btn-primary">Save</button>
</div>
</form>
</div>
jQuery
$("#editButton").click(function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
$.ajax({
url: 'getcontact.php',
type: 'POST',
data: 'id='+uid,
dataType: 'json',
success: function(response){
$("#nameInput").val(result[0]);
$("#companyInput").val(result[1]);
$("#posInput").val(result[2]);
$("#contactInput").val(result[3]);
$("#emailInput").val(result[4]);
$("#genderInput").val(result[5]);
}
});
});
getcontact.php
<?php
include("dbconnect.php");
$id = $_POST['id'];
$result = mysqli_query($link, "SELECT * FROM businesscontact WHERE id=$id");
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = $row['*'];
}
echo json_encode($rows);
?>
1 - you are sending a encoded json from your php file and use it directly from you javascript code which is invalid so to speak,
2 - you are sending the data object to php using ajax wrongly, it should be as follows instead data: {id: uid},
3 - you are declare the wrong data-id , it should be as follows: var uid = $(this).attr('data-id');
you need to decode your json response as follows:
var uid = $(this).attr('data-id');
$.ajax({
url: 'getcontact.php',
method: 'POST',
data: {id: uid},
success: function(response){
var result = JSON && JSON.parse(response) || $.parseJSON(response);
...
// rest of your code
...
Update
and you have an issue in this part:
while($row = mysqli_fetch_array($result)){
$rows[] = $row['*'];
}
to add the whole array you need to do as follows:
while($row = mysqli_fetch_array($result)){
$rows[] = $row;
}
My view Page :
<form id="myForm" >
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control datepicker pull-right" name="from_date" placeholder="From"> // want this value in my modal box
</div>
</div>
<div class="col-md-6">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control datepicker pull-right" name="to_date" placeholder="To"> // want this value in my modal box
</div>
</div>
<div class="col-md-12">
<br/>
<center><button class="btn btn-success" onclick="search_sale_return()"><i class="glyphicon glyphicon-plus"></i> Create New Stock</button></center> // on this click call the modal
</div>
</form>
JavaScript
<!-- Search sale return -->
function search_sale_return()
{
save_method = 'sale_return';
$('#form_sale_return')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('PharmacyController/search_sale_return')?>/" + 1, // bring value from database via controller in json_encode form
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="ph_name"]').val(data.from_date);
$('#modal_sale_return').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Sale return'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Modal
<!-- Bootstrap Receptionist modal -->
<div class="modal fade" id="modal_sale_return" role="dialog">
<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>
<h3 class="modal-title">Stock</h3>
</div>
<div class="modal-body form">
<form action="#" id="form_sale_return" class="form-horizontal">
<input type="hidden" value="" name="ph_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Medicine Name</label>
<div class="col-md-9">
<input name="ph_name" placeholder="Medicine Name" class="form-control" type="text">
<input name="ph_clinic_id" value="<?php echo $userinfo['id']; ?>" type="hidden">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="col-md-12">
<br/>
<table id="table_account" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Transaction Id</th>
<th>Patient Id</th>
<th>Ammount payed</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
This is my code , here i would like to get the value from form and than use it in my controller via javascript code and get json data and display it on my modal box
My problem :: on submit either i get link to controller or my modal (i wanna go to controller and from there i wanna go to modal in just one click button)
Fast example:
FORM:
<form id="myForm">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input type="text" class="form-control datepicker pull-right" name="from_date" placeholder="From" /> // want this value in my modal box
</div>
<div class="col-md-6">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input type="text" class="form-control datepicker pull-right" name="to_date" placeholder="To" /> // want this value in my modal box
</div>
</div>
<div class="col-md-12">
<br/>
<center>
<button class="btn btn-success" type="submit">
<i class="glyphicon glyphicon-plus">
</i> Create New Stock
</button>
</center>
// on this click call the modal
</div>
</form>
Modal:
<!-- Bootstrap Receptionist modal -->
<div class="modal fade" id="modal_sale_return" role="dialog">
<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>
<h3 class="modal-title">Stock</h3>
</div>
<div class="modal-body form">
<form action="#" id="form_sale_return" class="form-horizontal">
<input type="hidden" value="" name="ph_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Medicine Name</label>
<div class="col-md-9">
<input name="ph_name" placeholder="Medicine Name" class="form-control" type="text">
<input name="ph_clinic_id" value="<?php echo $userinfo['id']; ?>" type="hidden">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="col-md-12">
<br/>
<table id="table_account" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Transaction Id</th>
<th>Patient Id</th>
<th>Ammount payed</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="btnSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
Script:
<script>
$(function() {
$('form#myForm').on('submit',function(event) {
//get value
event.preventDefault();
var from_date = $(this).find('input[name="from_date"]').val();
var to_date = $(this).find('input[name="to_date"]').val();
//get data $_GET
$.ajax({
url: "<?php echo site_url('PharmacyController/search_sale_return')?>", // bring value from database via controller in json_encode form
type: "GET",
data: {from_date: from_date,to_date:to_date},
dataType: "JSON",
success: function(data) {
var modal = $('#modal_sale_return').modal('show');
modal.find('[name="ph_name"]').val(data.name);
modal.find('.modal-title').text('Sale return');
modal.find('#form_sale_return').trigger('reset');
modal.find('.help-block').empty();
modal.find('.form-group').removeClass('has-error');
//etc
//save in modal
$(modal).on('submit','form#form_sale_return',function(e) {
e.preventDefault();
var form = $(this);
var ph_name = form.find('[name="ph_name"]').val();
//etc
$.ajax({
url: "<?php echo site_url('PharmacyController/save')?>",
type: "post",
data:{ph_name:ph_name},
success: function(response) {
alert('SUCCESS')
},
error: function(xhr) {
alert('ERROR');
}
});
});
$('#modal_sale_return').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Sale return'); // Set title to Bootstrap modal title
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
});
</script>
I not tested... you try :)
Use
$('#modal_sale_return').modal();
to manually open the modal
Sending form data to controller :
$('#myForm').submit(function(e){
var ajaxForm = $(this)[0];
var formData = new FormData(ajaxForm);
$.ajax({
url: 'url',
type: 'POST',
data: formData,
success: function (result) {
},
error : function() {
}
});
});
i have a page where I have two buttons, one that opens a modal, and another one that only submits.
I have a .click event on the second button. If i go on the page and click the second button the click event goes fine, BUT if i first open the modal, close it and then i hit the second button, the first time does nothing and the second time it fires the .click event.
I would like to always fire the click event.
this is my code
$(document).ready(function(){
var focusout = false;
$(".prueba").click(function () {
if (focusout == false) {
focusout = true;
return;
}
});
var validator =$('#form1').validate(
{
ignore: "",
rules: {
parametros: {
required: function() { return focusout == true; },
},
terminos: {
required: function() { return focusout == true; },
}
},
highlight: function(element) {
$(element).closest('.grupo').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.grupo').removeClass('has-error');
}
});
$(".cancel").click(function() {
validator.resetForm();
});
}); // end document.ready
button 1:
<button type="submit" class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
button 2:
<button type="submit" class="btn btn-primary prueba" name="buscar">Buscar</button>
full form:
<form action="" method="post" id="form1" enctype="multipart/form-data">
<p>
<button type="submit" class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
<button type="submit" class="btn btn-primary" name="carga_masiva"><i class="icon-arrow-up"></i> Carga Masiva</button>
</p>
<br>
<div class="col-lg-1 grupo">
</div>
<div class="col-lg-10 grupo">
<div class="panel panel-default pagination-centered">
<div class="panel-heading">Búsqueda en Catálogo</div>
<div class="panel-body">
<div class="form-group ">
<div class="col-lg-6 grupo">
<input type="text" class="form-control " id="terminos" name="terminos" placeholder="Términos de búsqueda">
</div>
<div class="col-lg-6 grupo">
<select id="e1" name="parametros" style=" width:80%">
<option></option>
<option value="1" >Autor</option>
<option value="2" >Título</option>
</select>
</div>
</div>
<br> <br>
<div style="text-align:center">
<button type="submit" class="btn btn-primary prueba" name="buscar">Buscar</button>
</div>
</div>
</div>
</div>
<div class="col-lg-1 grupo">
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" name="myModal" data-backdrop="static" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-wide">
<div class="modal-content">
<div class="modal-header">
<button type="submit" class="close cancel" data-dismiss="modal" aria-hidden="true">×</button>
{if isset($smarty.post.nueva_articulo) }
<h4 class="modal-title">Nueva Articulo</h4>
{/if} </div>
<div class="modal-body">
{if isset($smarty.post.nueva_articulo) }
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_titulo" class="control-label">Título</label>
<input type="text" class="form-control input-sm" name="art_titulo">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_enlace" class="control-label">Enlace</label>
<input type="text" class="form-control input-sm" name="art_enlace">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="aut_id" class="control-label">Autor(es)</label>
<input type='hidden' id='e13' name="autores" style='width:100%'/>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_contenido" class="control-label">Contenido</label>
<textarea class="form-control input-sm" name="art_contenido" rows="5" ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="etiquetas" class="control-label">Etiquetas</label>
<input type="text" id="e12" name="etiquetas" style="width:100%">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="foto" class="control-label">Imagen</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Buscar… <input type="file" name="foto">
</span>
</span>
<input type="text" class="form-control" name="nombre" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<div class="checkbox">
<label>
<input type="checkbox" name="rating" value="si"> Habilitar Rating y Reviews
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="redes" value="si"> Habilitar Compatir en Redes Sociales
</label>
</div>
</div>
</div>
{/if}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default cancel" data-dismiss="modal" name="cerrar">Cerrar</button>
{if isset($smarty.post.nueva_articulo) }
<button type="submit" class="btn btn-primary" name="insertar_articulo">Guardar Cambios</button>
{/if}
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
<!-- /.modal -->
</form>
They are both of type submit. You should only have 1 submit button on a form
Button 1 could just be a button
<button class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
If you want, you can create a Form Object in javascript and generate it dynamically. That will do that you don't need to depend of the submit and forms, just fill the form object with the inputs that you want programatically (that even accept files or images).
But anyway, it seems that you have more than one click events on the same button if the one you want is triggering at the second attempt. You could try to play with event.preventDefault or $.unbind.
As you said taht you need to submit the inputs of the modal, try to place the content of the modal inside the tag and remove the submit type of one of the buttons.