Update Database Record with Ajax in Codeigniter - javascript

I am trying to update database records using ajax from the ajax response, getting success message but the actual database records are not updated at all. But it wonder how the ajax response should throw the success message while the query is not updating the database.
VIEW:
// AJAX code to update the database
// update marks when form is submitted
$('#updateMarks').on('submit',function(event) {
event.preventDefault();
var practical_mark = $("#mark_written").val();
var written_mark = $("#mark_practical").val();
var comment = $("#comment").val();
var mark_id = $("#mark_id").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
alert("success");
},
error: function(){
alert("Error");
},
});
});
<?php foreach($marks as $row2): ?>
<form method="post" role="form" id="updateMarks">
<tr>
<td class="text-center"><?php echo $student['name']; ?></td>
<td>
<!-- create two col table for marks category -->
<table class="table table-bordered table-hover toggle-circle">
<thead>
<tr>
<th data-toggle="true" class="text-center"><?php echo get_phrase('written_exam'); ?></th>
<th data-toggle="true" class="text-center"><?php echo get_phrase('practical_exam'); echo get_phrase('_(out_of_100)'); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><input type="number" value="<?php echo $row2['written_mark_obtained'];?>" id="mark_written" name="mark_written" class="form-control" /></td>
<td class="text-center"><input type="number" value="<?php echo $row2['practical_mark_obtained'];?>" id="mark_practical" name="mark_practical" class="form-control"/></td>
</tr>
</tbody>
</table>
<!-- end create two col table for marks category -->
</td>
<td class="text-center"><textarea class="form_control" id="comment" name="comment" rows="4" > <?php echo $row2['comment'] ?> </textarea></td>
<td class="text-center">
<input type="hidden" id="mark_id" name="mark_id" value="<?php echo $row2['mark_id'];?>" />
<button type="submit" class="btn btn-block btn-success btn-md"><i class="icon pe-pen" aria-hidden="true"></i><?php echo get_phrase('update'); ?></button>
</td>
</tr>
</form>
<?php endforeach; ?>
Controller:
function exam_marks_update(){
$data['written_mark_obtained'] = $this->input->post('written_mark');
$data['practical_mark_obtained'] = $this->input->post('practical_mark');
$data['comment'] = $this->input->post('comment');
$this->crud_model->update_student_marks($data, $this->input->post('mark_id'));
}
MODEL
function update_student_marks($data, $mark_id){
$this->db->where('mark_id', $mark_id);
$this->db->update('mark', $data);
}

Jquery ajax success callback function is always called if the request to server succeeds. You need to return response data from server to verify when database operation was successful or not. I have edited your code , this might work for you.
MODEL
function update_student_marks($data, $mark_id){
.....
return $this->db->update('mark', $data);
}
Controller::
function exam_marks_update(){
.....
if($this->crud_model->update_student_marks($data, $this->input->post('mark_id'))){
echo json_encode(array('success' => true));
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
}
View
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
dataType :'json',
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
if (response.success === true){
alert("success");
} else {
alert('failed');
}
},
error: function(){
alert("Error");
},
});

Your Controller retrieving inputs which doesn't exists... you need to pass your name, id as inputs and not the value which you echo... see as Controller:
function exam_marks_update(){
$data = array(
'written_mark_obtained' => $this->input->post('written_mark'),
'practical_mark_obtained' => $this->input->post('practical_mark'),
'comment' => $this->input->post('comment')
);
$this->db->where('mark_id', $this->input->post('mark_id'));
$this->db->update('mark', $data);
}
and change this:
var comment = $("#comment").val();
to
var comment = $("#comment").html();
As comment is textarea...

Related

Refresh table in success of ajax function

I have the following table where I have two buttons to delete and update.
When I delete it automatically removes the table row.
But when I edit the line and change the state, the user still sees the line, where it gets confusing because they don't know the lines that have already been edited and the ones left to edit.
So when changing state the row should also disappear from the table.
Code:
<div id="spoiler2" class="esconde">
<table class="table table-responsive" id="employee_table2">
<h1 style="font-size: 30px"><strong>Pedidos de Manutenção</strong></h1>
<thead>
<tr>
<th>Data</th>
<th>Valência</th>
<th>Descrição</th>
<th>Colaborador</th>
<th>Estado</th>
<th>Ação</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
<?php do{ ?>
<tr id="<?php echo $produto2["Id"]; ?>">
<td><?php echo $produto2["DataRegisto"]; ?></td>
<td><?php echo $produto2["Destino"]; ?></td>
<td><?php echo $produto2["Descricao"]; ?></td>
<td><?php echo $produto2["nome"]; ?></td>
<td><?php echo $produto2["Estado"]; ?></td>
<td><button type="button" name="edit" data-id="<?php echo $produto2["Id"]; ?>" id="open_<?php echo $produto2["Id"]; ?>" data-target="#add_data_Modal2" class="btn btn-warning btn-sm edit_data2" ><span class="glyphicon glyphicon-pencil"></span></button></td>
<td><button class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-trash"></span></button></td>
</tr>
<?php } while($produto2 = $result2->fetch_assoc()); ?>
</tbody>
</table>
</div>
js:
$(document).on('click', '.edit_data2', function(){
var employee_id2 = $(this).data('id');
$.ajax({
url:"./editarmanutencao",
method:"POST",
cache: false,
data:{employee_id2:employee_id2},
dataType:"json",
success:function(data){
console.log(data);
$('#Id2').val(data.Id);
$('#Tratamento').val(data.Tratamento);
$('#Estado2').val(data.Estado);
$('#Prestador').val(data.Prestador);
$('#employee_id2').val(data.Id);
$('#insert2').val("Gravar");
$("#add_data_Modal2").modal("show");
}
});
});
function inserir_registo2()
{
var dadosajax = {
'Id' : $("#Id2").val(),
'DataTermino' : $("#DataTermino").val(),
'Tratamento' : $("#Tratamento").val(),
'Estado' : $("#Estado2").val(),
'Prestador' : $("#Prestador").val()
};
$.ajax({
url: './resolucaomanutencao',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$("#add_data_Modal2").modal("hide");
}
});
}
How can I remove the table row by changing ajax's success state?
If i understand correctly, you want to remove row from table after successful Edit operation.
If this is the case, you can use following code...
function inserir_registo2()
{
let rowToBeRemoved = $("#"+$("#Id2").val());
var dadosajax = {
'Id' : $("#Id2").val(),
'DataTermino' : $("#DataTermino").val(),
'Tratamento' : $("#Tratamento").val(),
'Estado' : $("#Estado2").val(),
'Prestador' : $("#Prestador").val()
};
$.ajax({
url: './resolucaomanutencao',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$("#add_data_Modal2").modal("hide");
if(<<Condition>>) // in case you want to validate something before removing row
{
rowToBeRemoved.remove();
}
}
});
}
Save a reference to the parent row before the ajax call (e.g. var row = $(this).closest('tr')) and then, on success, remove it by row.remove().

How to use jQuery POST instead of html form to delete table entry

I am trying to delete the table entry without opening the .php file using jQuery post.
The whole thing works without problems when I just use the usual html post form.
The alert(data) does not trigger, it only adds ".../?player_id_del=1" or whatever ID click into the URL.
What am I doing wrong?
Here is some of my index.php, i get the whole data from a database:
<table class = "table table-hover">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr>
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<form id="del-form">
<div>
<input type="number" id="player_id_del" name="player_id_del" value="<?php echo htmlspecialchars($player["PLAYER_ID"]); ?>" />
</div>
<div>
<button type="submit" id="submit-btn" class="btn btn-danger">Delete</button>
</div>
</form>
<script>
$("#submit-btn").click(function(){
$.post("deletePlayer.php", $("#del-form").serialize() , function(data) {
alert(data);
});
});
</script>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
Here is my deletePlayer.php:
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
echo "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
echo "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
?>
Thank You in advance for any help!
By default jQuery's click event reload the document so, you should try using,
$("#submit-btn").click(function(e){
e.preventDefault();
e.stopPropagation();
});
Also instead of $.post, try using $.ajax
There are many issues in your code
E.g IDs for form and delete input button are repeating (id of element should not be same it should be unique),
The following code is the tested and working.
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
$response = array();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
$response["success"] = 1;
$response["id"] = $player_id;
$response["message"] = "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
$response["success"] = 0;
$response["message"]= "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
echo json_encode($response);
?>
<table class = "table table-hover" id="mPlayersTabel">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr id= "<? echo $player["PLAYER_ID"]; ?>">
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<div>
<button type="submit" player-id="<? echo $player["PLAYER_ID"]; ?>" class="btn btn-danger" >Delete</button>
</div>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".btn-danger").on("click touchend" , function(){
var id = $(this).attr("player-id");
$.ajax({
url: 'deletePlayer.php',
type: 'POST',
data: {
player_id_del: id
},
dataType: 'json',
success: function (response) {
//Add this line and try
response = JSON.parse(JSON.stringify(response));
alert(response['message']);
switch (response['success']) {
case 1:
$("#mPlayer" + response['id']).remove();
break;
}
}
});
});
});
</script>

id on click of button in PHP

I am working on PHP admin panel, where I want to show list of users in the form of HTML table. In each table row there is one button where admin can send notification to the selected user.
I have created the table from below code and shown as expected.:
<div class="table">
<div style="overflow: auto;height: 400px; width: 100%;">
<form method='post'>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>Id</th>
<th>Package</th>
<th>Date</th>
<th>Referring Agent</th>
<th>Content Control</th>
</tr>
<?php if(!empty($records)){
foreach($records as $k=>$v){
?>
<tr>
<td><?php echo $v['id']; ?></td>
<td><h3><?php echo $v['firstname']; ?></h3></td>
<td><?php echo $v['lastname']; ?></td>
<td><?php echo $v['email']; ?></td>
<!--<td><input id='<?php echo $v['id']; ?>' type='submit' name ='send_notification' value='Send Notification'></td>-->
<td>
<div class="pagging">
Send Notification
</div>
</td>
</tr>
<?php
}
}else{
?>
<tr>
<td colspan="5" align='center'><?php echo "No record added yet"; ?>
</tr>
<?php
}
?>
I want to send the 'id' of each row to some function on click of 'send notification' where I can perform DB operations in PHP. I am not able to do that. I want on click of 'send notification' a function in php will execute which will perform some DB operation.
You need to use AJAX. Use below code.
AJAX Code
<script>
function sendNotification(id)
{
$.ajax({
type: "POST",
url: "update.php",
data: {id:id},
success: function(html) {
alert("Updated successfully");
}
});
}
</script>
PHP Code : update.php
<?php
if(isset($_POST['id']))
{
//Update query and operation here
}
?>
Download latest and require jquery from here. Click Here

ajax delete post asynchronously - php

I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});

Ajax response not updating in php while loop

I am having a slight problem figuring out why this ajax response isn't updating properly. I have a php while loop which lists gallerys in text format, i am using . It is getting details from the php page but only for one result so essentially when you hover over the name a qtip tooltip box pops up so you can edit the name of the gallery. The problem is it only lists one result for all results in the loop.
PHP & HTML
<?php
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE UserID='".$_SESSION['user_id']."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$BaseHeight = 150;
$GalleriesBoxHeight = $BaseHeight + ( 20 * $MemberGalleriesCount );
echo '
<div id="ManageGalleries" style="height: '.$GalleriesBoxHeight.'px" align="center">
<div id="ManageGalleriesHeader">Manage Galleries</font></div><br><br>
<font color="#000000"><b>Click Gallery To Edit</b></font><br><br>
';
while($GalleryData = $MemberGalleriesQuery->fetch_assoc())
{
echo '>> <b><a class="EditGallery" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
}
echo '<br><br></div>';
}
$MemberGalleriesQuery->free();
?>
JAVASCRIPT:
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
$.ajax({ //Make the ajax request
url: link,
cache: false
}).done(function( html ) { //On complete run tooltip code
//Display tooltip code goes here, returned text is variable html
$('.EditGallery').qtip({
content: {
text: html
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$('.EditGallery').qtip('click', true);
$(".EditGallery").page();
});
});
CONTENTS OF Crowork.Backend/Crowork.EditGallery.php
if ( isset( $cleanGet['action'] ) && $cleanGet['action'] == 'EditGallery' ){
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE GalleryID='".$cleanGet['gallerykey']."' AND UserID='".$SessionUserID."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$GalleryData = $MemberGalleriesQuery->fetch_assoc();
}?>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<input type="hidden" name="GalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID']?>">
<input type="submit" name="DeleteGallery" value="Delete Gallery">
</form>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<table border="0" width="100%">
<tr>
<td colspan="2" align="center"><font size="-1"><b>NOTE:</b> Letters & Numbers Only</font></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="GalleryName" size="30" value="<?php echo $GalleryData['GalleryName']?>"></td>
</tr>
<tr>
<td align="right" colspan="2">
<input type="hidden" name="OriginalGalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID'] ?>">
<input type="submit" name="EditGallery" value="Edit Gallery">
</td>
</tr>
</table>
</form>
<?php }?>
PREVIEW:
http://www.bigjohn863.com/mini-upload-form/uploads/ajaxproblem.png
See how all three are the same results.
Try:
$('.EditGallery').each(function()
{
$(this).qtip({
content: {
text: "Loading...",
ajax: {
url:$(this).attr('href'),
type: "GET",
success: function(data, status) {
this.set('content.text', data);
}
}
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$(this).qtip('click', true);
});
http://jsfiddle.net/st0j8nLy/
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
....
everytime you are calling $('.EditGallery'). $('.EditGallery'). is an array, you need to change all references to $('.EditGallery') that is within the loop to $(this):
var link = $(this).attr('href'); //Gets link url
You Might be need to create dynamic id so you can call proper ajax.
please modify your ajax call as below
$gid=$GalleryData['GalleryID'];
echo '>> <b><a onclick="editgalary($gid)" id="EditGallery_$gid" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
replace this code in while loop.
function editgalary(galaryid){
var link = $('#EditGallery_'+galaryid).attr('href');
//ajax code as it is.
}
try and let me konw

Categories

Resources