Send data on modal box on mvc - javascript

In my view I have the link, the modal box, and script. I have my ID on my modal but i can't send it on my controller.
The link:
<span class="glyphicon glyphicon-pencil"></span>
My modal:
<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body edit-content"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
And my script:
$( document ).ready(function() {
$('#edit-modal').on('show.bs.modal', function(e) {
var $modal = $(this),
Id = e.relatedTarget.id;
$.ajax({
method: 'POST',
url: 'index.php?section=gestion-salles',
data: 'id_salle='+Id,
success: function(data) {
alert(data);
$modal.find('.edit-content').html(Id + '<?php echo $test; ?> ' + 'id= <?php echo $id; ?>');
}
});
})
});
In my controller I defined a variable, $test, and I recovered it. But I defined my variable $_POST['id_salle'] but can't recover it. I would like to send it to the controller and then do the processing but I can't.
Thank you.

My controller:
include_once('modele/set_salles.php');
include_once('modele/get_salles.php');
include_once('controleur/modal.php');
if(isset($_POST['bouton']))
{
if($_POST['titre'] !='' && $_POST['description'] !='' && $_POST['adresse'] !='' && $_POST['cp'] !=''){
$tmp_name = $_FILES["photo"]["tmp_name"];
$name = $_FILES["photo"]["name"];
set_salles(addslashes($_POST['titre']), addslashes($_POST['description']), $name, $_POST['pays'], $_POST['ville'], addslashes($_POST['adresse']), $_POST['cp'], $_POST['capacite'], $_POST['categorie']);
$uploads_dir = 'img/';
move_uploaded_file($tmp_name, "$uploads_dir/$name");
} else {
$remplir = '<p style="color:red">merci de remplir tous les champs</p>';
}
}
$salles = get_salles();
foreach($salles as $cle => $salle)
{
$salles[$cle]['titre'] = htmlspecialchars($salle['titre']);
$salles[$cle]['description'] = nl2br(htmlspecialchars($salle['description']));
}
$id = $_POST['id_salle'];
$test = 'Hello';
// On affiche les page (vues)
include_once('vue/include/header.php');
include_once('vue/include/navbar.php');
include_once('vue/gestion-salles.php');
include_once('vue/include/footer.php');

Related

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

My modal is not updating new data from cookie

I have problem with updating modal with new data from cookie. When I select new item in table and push it to cookie. Then it wan't to update my modal view when i press button.
Can somebody figured out why it's not working.
<script>
var selVal = new Array();
$("tbody tr").click(function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
var pId = $(this).find('td:first').data("id"); // Get id num from selected
//Remove item from array
var i = selVal.findIndex(x => x.pId === pId);
if (i !== -1) {
selVal.splice(i, 1);
}
} else {
$(this).addClass("selected");
var pId = $(this).find('td:first').data("id"); // Get id num from selected
var pNum = $(this).find('td:first').html(); //Get pnum from selected
var newObjArr = {pId, pNum};
selVal.push(newObjArr);
}
createCookie(selVal);
});
function createCookie(selVal) {
var json_str = JSON.stringify(selVal); // JSON Serialize
// Define/Set cookie
Cookies.set("Cookie_<?php echo $id?>", json_str, {expires: 1});
}
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">XXXXXXXXXXXXXXXX</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<button type="button" id="refdata_btn" class="btn btn-info">Refresh</button>
<p><label>Airline: </label><input type="text" name='xxxxxx'></p>
<p><label>Date: </label> <input type='date'></p>
<?php
$cookie_name = 'Cookie_' . $id;
if (isset($_COOKIE[$cookie_name])) {
$decjson = json_decode($_COOKIE[$cookie_name], true);
foreach ($decjson as $d) {
echo '<p>' . $d['pNum'] . '</p>';
}
} else {
echo 'Cookie not exist';
}
?>
</div>
<div class="modal-footer">
<button type="button" id='btn_later' class="btn btn-secondary" data-dismiss="modal">Later</button>
<button type="button" class="btn btn-primary">Send</button>
</div>
</div>
</div>
</div>
When I see this it is not give me espacially logical why not it is reseting or overriding previous data.
Thanks,
ZS

Error when sending variable from AJAX to PHP

I'm generating table rows with data from a database.
Below is my code:
<table class="table table-hover" id="dashEventTable">
<thead>
<tr>
<th>Created at</th>
<th>Seminar Name</th>
<th>Quota</th>
<th>Location</th>
<th>Option</th>
<th style="display:none"></th>
</tr>
</thead>
<tbody script="javascript">
<?php
$one = 1;
$Lihat="SELECT * FROM event where status = '$one'";
$Tampil = mysqli_query( $db, $Lihat );
while ( $hasil = mysqli_fetch_array ( $Tampil ) ) {
$id_event = ( $hasil['id_event'] );
$nama_event = ( $hasil['nama_event'] );
$lokasi = ( $hasil['lokasi'] );
$kuota = ( $hasil['kuota'] );
$created_at = ( $hasil['created_at'] );
{ ?>
<tr>
<td class="created_at"><?php echo date( 'Y-m-d h:i a', strtotime( $created_at ) ); ?></td>
<td class="event_name"><?php echo "$nama_event"; ?></td>
<td class="kuota"><?php echo "$kuota"; ?></td>
<td class="lokasi"><?php echo "$lokasi"; ?></td>
<td>
<a class="btn btn-xs btn-danger btn_delete" data-toggle="modal" href="#deleteDashEvent"><i class="fa fa-trash"></i></a>
</td>
<td class="event_id" style="display:none"><?php echo "$id_event"; ?></td>
</tr><?php }
} ?>
</tbody>
</table>
Now when I click on the button inside the rows, it does two things, the first is going to this JavaScript function:
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
alert( event_id );
}
});
});
From the alert and console log, I saw that I got the correct ID for the event id of the row. The data will then be sent to the PHP file above, and inside that PHP is this:
<?php
if ( isset( $_POST['send'] ) ) {
$id_event = $_POST['send'];
} else {
echo "The data has not been received!";
}
The second thing it does is go to this div for the delete confirmation:
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
</form>
When the DELETE button is clicked, it will then go to this PHP file:
<?php
session_start();
include( "config.php" );
if ( isset( $_POST['admin_delete_event'] ) ) {
include( "contain_data.php" );
$zero = 0;
$delete_query = "UPDATE event, jadwal_acara, waktu_pendaftaran
SET event.status = '$zero', jadwal_acara.status = '$zero', waktu_pendaftaran.status = '$zero'
WHERE event.id_event = '$id_event'
AND jadwal_acara.id_event = '$id_event'
AND waktu_pendaftaran.id_event = '$id_event'";
if ( mysqli_query( $db, $delete_query ) ) {
$delete = "Data has been deleted";
echo $delete;
} else {
echo "Error: " . $delete_query . "<br>" . mysqli_error( $db );
}
} else {
echo "The button is not detected!";
}
The problem I am having is that I received this error when I click the delete confirmation button:
The data has not been received!
Undefined variable: id_event in...
Which means that I fail in sending the data.
What am I doing wrong and how can I resolve it?
EDIT: after adding error handling to the php file, the value sent by the ajax is null instead of the id_event, do you guys know why?
Update your AJAX With:
$.ajax({
url: "contain_data.php",
method: 'post',
data : 'send='+event_id,
success:function(){
alert(event_id);
}
});
try to pass your event_id using this way
data : 'send='+event_id,
because you have taken
method: 'post',
Hope it will help
I got your error . Upto submit your first form through is correct when you go for delete conformation you miss that event_id and you just using that one in you "admin_delete_event.php" file that why it giving error
Undefined variable: id_event in...
Now just add an hidden input field in form and submit it then the event_id will be available to you.
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
<input type="hidden" name='event_id' value='id' id='event'>
</form>
And just change this in your 1st Ajax
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
$('#event').val(event_id);
alert( event_id );
}
});
});
Then it will work fine.

sending error message to view with codeigniter

I have a form that submit email and have a condition if the submitted email isn't verified (status = 1) then it fails to insert to the user_driver table. What I want to achieve is how can I show error message like "Please verify your email" when the user click on add button after filling the email field? I am using jquery to send input post to controller and my form is inside modal bootstrap. It hits success function even though the requirement is not met (email_verified = 1) and then reload the page. So, I am a bit confuse how to show the error message.
My view:
function add_driver()
{
user_email = $("#user_email").val();
$.ajax
({
url : site_url+'portal/add_driver',
type: "POST",
//dataType: "json",
data:{user_email: user_email},
success: function(data)
{
$("#add_driver_modal").modal("hide");
location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Email already registered');
location.reload();
}
});
};
<div class="modal fade" id="add_driver_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" 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">ADD DRIVER</h4>
</div>
<div class="modal-body" id='add'>
<div class="row" id="add_driver_form">
<input type="hidden" name="user_id" id="user_id" />
<div class="col-sm-4">
<input type="text" class="form-control input-lg" autocomplete="off" id="user_email" name="user_email" placeholder="Email" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add" type="button" class="btn btn-primary btn-md" onclick=add_driver()>Add</button>
</div>
</div>
<div id="form_submit_result"></div>
</div>
</div>
My controller:
public function add_driver()
{
$user_email = $this->input->post('user_email');
$array = array(
'user_email' => $user_email,
'email_verified' => 1,
'phone_verified' => 1
);
$this->db->select('*');
$this->db->where($array);
$this->db->from('user');
$query = $this->db->get();
$result = $query->row_array();
$match_id = $result['user_id'];
$match_email = $result['user_email'];
if(!is_null($result))
{
$data_user_driver = array(
'user_id' => $match_id,
'user_email' => $match_email
);
$this->db->insert('user_driver',$data_user_driver);
}
}
You may add a p tag in your modal inside modal-body like
....
<div class="modal-body" id='add'>
<p style="display:none;" id="error" class="alert alert-danger"></p>
...
and add a else block and send any message if no result found (in add_driver method) like
...
if(!is_null($result)){
$data_user_driver = array(
'user_id' => $match_id,
'user_email' => $match_email
);
$this->db->insert('user_driver',$data_user_driver);
} else {//if email not verified
echo 'err';
}
....
Now check this result in your ajax success
....
success: function(data){
if(data == 'err'){
$('#error').show().text('Please verify your email');
return false;
}
$('#error').hide();
$("#add_driver_modal").modal("hide");
location.reload();
},
....

Codeigniter: Ajax sending id & name but function is receiving only id

I'm getting the id but not the name, what's wrong i'm doing ?
Please take a look at my CI code and ajax function below:
This is View on which i'm calling ajax:
<div class="modal fade" id="myModal<?php echo $values->season_id; ?>"
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">Update Seasons</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="hiddenValue" name="hiddenValue" value="<?php echo $values->season_id; ?>">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Season Name:
</label>
<div class="title_right">
<div class="input-group">
<input type="text" class="form-control" name="update_name" id="update_name" value="<?php echo $values->names; ?>">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" id="submit" value="Save changes">
</div>
</div>
</div>
</div>
This is Ajax Function:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
alert("Ajax function started working");
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
dataType: 'json',
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
alert("changes made");
}
}
});
});
});
And here i'm trying to capture the value:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$result = $this->model_season->update_season($update_id,$update_name);
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
You use
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
but where your $query. As your code It should have as following
if ($result)
{
$data = array(
'season_id' => $result->season_id,
'names' =>$result->names
);
echo json_encode($data);
}
Now use $result->season_id instead of $query->season_id and make sure you use row() method in your model update_season() for returning desired values

Categories