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

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

Related

Show a modal with receipt after submit form (Codeigniter)

My target is, after I submit the form, there'll be a modal after reload that shows the transaction details. I have made a next page transaction details, however, it is much better to do the receipt php on onload modal after submission. But I don't know how to start. I provided a screenshot below of my current work. Any help will be appreciated. Thank you
View:
<button type="button" data-id="<?php echo $rows->userID; ?>" data-firstname="<?php echo $rows->firstname; ?>" class=" showmodal btn btn-success btn-sm text-bold " data-toggle="modal" data-target="#fundModal"><i class="fas fa-hand-holding-usd mr-1"></i> FUND </button> // This button shows modal when clicked
//This is my modal for transferring fund
<div class="modal fade" id="fundModal" tabindex="-1" role="dialog">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header bg-green">
<h5 class="modal-title text-bold" id="exampleModalLabel">Fund</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body bg-white text-center">
<label><h3>Transfer fund:</h3></label>
<br>
<!-- FORM -->
<div id="errorMessage" style="color: red; display: none; font-size: 11px"></div>
<form method="POST" action="<?php echo site_url('network/form_validation');?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<input type="hidden" id="firstname" name="receiptname" value="<?php echo $rows->firstname; ?>">
<div class="col-lg-12" >
<input type="text" placeholder="Enter Amount" name="amount" autocomplete="new-amount" value="" class="form-control number" id="box" >
<br>
<?php echo $this->session->flashdata('warning'); ?>
<input type="password" placeholder="Enter Password" autocomplete="new-password" name="fundpass" class="form-control" id="password" required ">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Controller:
public function form_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$this->load->library('form_validation');
$this->form_validation->set_rules('fundpass', 'fundpass', 'callback_password_check');
if($this->form_validation->run() == false) {
echo '<script>alert("Invalid input of Password!");</script>';
redirect('network/agents', 'refresh');
}
else {
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$fname = $this->input->post('receiptname');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
$this->networks->insert_data($data1);
// return json_encode($data1);
$_SESSION["amount"] = $this->input->post("amount");
$_SESSION["receivedID"] = $id;
$_SESSION["receiptFName"] = $fname;
$_SESSION["reference"] = $this->input->post("refNumber");
redirect(base_url() . "network/receipt");
}
else
{
$this->index();
}
}
}
public function password_check($fundpass)
{
$id = $this->session->userdata('uid');
if($this->session->userdata('password')!== md5($fundpass)) {
$this->form_validation->set_message('password_check', 'The {field} does not match');
return false;
}
return true;
}
Model:
function fundin($data)
{
// Fund in
$id = $this->input->post('userID');
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set currentPoints = currentPoints + ? where userID = ?";
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['userID']));
}
function insert_data($data1)
{
// fund out
$sql1 = "select * from transaction_ledger where userID = ? order by ledgerID desc limit 0,1";
$Q1 = $this->db->query($sql1, $data1['userID']);
$R1 = $Q1->row_array();
$ref= $this->session->userdata('userID') + time ();
$idata1 = array(
'userID' => $data1['userID'],
'transactionSource' => 'FR',
'transType' => 'out',
'refNumber' => 'FO' . $ref,
'amount' => $data1['amount'],
'currentBalance' => $R1['currentBalance'] - $data1['amount'],
'previousBalance' => $R1['currentBalance'],
'remarks' => 'transfer fund to agent',
);
$this->db->insert('transaction_ledger', $idata1);
$sqlUpdate = "update users set currentPoints = '".$idata1['currentBalance']."', dateUpdated = '".date('Y-m-d h:i:s')."'where userID = ?";
$this->db->query($sqlUpdate, $idata1['userID'] );
}
You can programmatically open the bootstrap modal when document ready
Just like
$(document).ready(function(){
$("#fundModal").modal('show');
});
</script>
I would suggest to do with ajax call for better user experience.
$( "#formId" ).on('submit', function(e){
e.preventDefault();
let $form = $(this);
$.post( 'post-url-here', $form.serialize(), function(result) {
var result = JSON.parse(result);
if( result.status == 'success' ) {
$("#fundModal").modal('show');
}
});
});

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.

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.

Send data on modal box on mvc

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');

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

Categories