How to delete row form ajax when it is deleted - php

hello i am trying to delete a row with check box delete when i delete any record it is deleting from database and i can see with refreshing page.
I want to delete the row without refresh how can i achieve that:
This is my listing code:
<tbody>
<?php while($staffResults=$staffQuery->fetch_assoc()){ ?>
<tr>
<td><input type="checkbox" class="staff-list" name="checked" value="<?php echo $staffResults['id_staff']; ?>"></td>
<td><?php echo $staffResults['staff_name']; ?></td>
<td><?php echo $staffResults['staff_email']; ?></td>
<td><?php echo $staffResults['staff_phone']; ?></td>
<td><?php $datetime = $staffResults['staff_registered'];
echo date("d-m-Y", strtotime($datetime)); ?></td>
</tr>
<?php } ?>
</tbody>
And delete button:
<button type="button" id="deleteStaffList" class="btn btn-sm btn-default" title="Remove"><i class="fa fa-trash-o"></i></button>
Here is my script and ajax code.
<script language="JavaScript">
$("#deleteStaffList").click(function()
{
$("#delshowMessageDiv").hide();
$("#delshowMessage").html('');
var deleteStaffList = $('.staff-list:checkbox:checked').map(function(){
return $(this).attr('value');
}).get().join(",");
console.log(deleteStaffList);
$.ajax({
url: "staffcontroller.php",
method: "POST",
data: { delData : deleteStaffList, 'action':'delete'},
dataType: "json",
success: function (response) {
if(response["success"]==true)
{
$("#delshowMessageDiv").hide();
$("#delshowSuccessMessageDiv").show();
$("#delshowSuccessMessage").html(response["message"]);
}else{
$("#delshowMessageDiv").show();
$("#delshowMessage").html(response["message"]);
}
},
error: function (request, status, error) {
$("#delshowMessageDiv").show();
$("#delshowMessage").html("OOPS! Something Went Wrong Please Try After Sometime!");
}
});
return false;
});
</script>

You can place 3 lines as follows: (// new lines -there comment- // till here)
<script language="JavaScript">
$("#deleteStaffList").click(function()
{
$("#delshowMessageDiv").hide();
$("#delshowMessage").html('');
var deleteStaffList = $('.staff-list:checkbox:checked').map(function(){
return $(this).attr('value');
}).get().join(",");
console.log(deleteStaffList);
$.ajax({
url: "staffcontroller.php",
method: "POST",
data: { delData : deleteStaffList, 'action':'delete'},
dataType: "json",
success: function (response) {
if(response["success"]==true)
{
$("#delshowMessageDiv").hide();
$("#delshowSuccessMessageDiv").show();
$("#delshowSuccessMessage").html(response["message"]);
}else{
$("#delshowMessageDiv").show();
$("#delshowMessage").html(response["message"]);
// new lines
$('.staff-list:checkbox:checked').each(function(i,e){
$(this).parents('tr').remove();
})
// till here
}
},
error: function (request, status, error) {
$("#delshowMessageDiv").show();
$("#delshowMessage").html("OOPS! Something Went Wrong Please Try After Sometime!");
}
});
return false;
});
</script>

Related

php variable value in a while loop for each row

I have a cancel button on each row of a table that is autopopulated in a while loop.
The $id resolves correctly but when I click on the cancel button all the active rows are modified. I only want the row that is concerned to be modified.
So in a while loop in php:
<tr id="dataTable">
<td id="nom"><?php echo $nom;?></td>
<td id="statut"><?php echo $statut;?> </td>
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" href="#" title="Annuler"
onclick="document.write('<?php
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$id."'";
$resultatannuler = $connexion->query($queryannuler); ?>'); location.reload(); 'return false';">Annuler</a>
</td>
</tr>
My problem is the 'statut' column is being updated for all the rows and not just the row where I click on the cancel button. Thanks if you can help.
UPDATE
I have tried to implement your different advices by using ajax. It's tough. I didn't specify in the original post that I am using a Wordpress framework. So I have modified #ssurli code to take into account wordpress
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" class="button delete" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
</td>
<script>
function cancelRecord(id) {
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {id:id},
action: 'delete_rdv',
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
console.log('The function is hooked up');
location.reload();
console.log('The function is hooked up2');
}
});
}
AND in my functions.php file
add_action( 'wp_ajax_delete_rdv', 'delete_rdv' );
add_action( 'wp_ajax_nopriv_delete_rdv', 'delete_rdv' );
function delete_rdv() {
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
}
I'm stuck on the very first hurdle.
The console is sending an error message :
admin.php?page=plugin-voc:1 Uncaught ReferenceError: cancelRecord is not defined
But my cancelRecord function is right after my button call so I don't understand this error.
Here the working code.
Update your table row as below:
<tr id="dataTable">
<td id="nom"><?php echo $nom;?></td>
<td id="statut"><?php echo $statut;?> </td>
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
</td>
</tr>
Add below js scripts to bottom of your html page. Include jquery cdn file only if not add to page already.
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
function cancelRecord(id) {
$.ajax({
type: 'post',
url: 'cancel.php', //use actual directory path, if not kept in root directory
data: {id:id},
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
location.reload();
}
});
}
</script>
Add PHP file having PHP code having DB query responsible for cancelling the record.
//cancel.php
<?php
$queryannuler = "UPDATE wp_RDV SET statut = 'Testy' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
Hope it will work for you. Feel free if you have any further query.
This was the original html request
<td id="<?php echo $id;?>" >
<a id="<?php echo $id;?>" class="button delete" href="javascript:void(0)" title="Annuler"
onclick="cancelRecord('<?php echo $id; ?>')">Annuler</a>
The javascript function was not defined when I put it in the same file as the php. I moved into the plugin index.js file and most importantly I moved this line:
action: 'delete_rdv',
into data {}
data: {
action: 'delete_rdv',
id:id},
Here is the complete javascript code:
jQuery( document ).ready(function($){ $('.button.delete').on('click', function(){ let id = $(this).attr('id'); cancelRecord(id); }); });
function cancelRecord(id) {
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {
action: 'delete_rdv',
id:id},
success: function(response) {
return;
},
error: function(jqXHR, status, error) {
alert('Error: Please refresh the page');
return;
},
complete: function() {
location.reload();
}
});
}
The ajax calls the function delete_rdv which I put in the functions.php file
add_action( 'wp_ajax_delete_rdv', 'delete_rdv' );
add_action( 'wp_ajax_nopriv_delete_rdv', 'delete_rdv' );
function delete_rdv() {
$queryannuler = "UPDATE wp_RDV SET statut = 'Annulé' WHERE id_RDV = '".$_POST['id']."'";
$resultatannuler = $connexion->query($queryannuler); //include connection file above
return $resultatannuler;
}
Special thanks to #jeprubio for kinda forcing to look the ajax way and to #sssurii for posting his code and answering my question.

how can i post data in Codeigniter using Ajax

How can i post data in Codeigniter using Ajax, am so confused this is the first time i do ajax and Codeigniter together
here is my ajax code
i tried to send the data to the controller method ;
This is my ajax
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url: baseURL+"admin/Products/add_product",
type:'post',
data:{productData:postData},
success:function(data){
}
});
});
});
this is my form
<?php $attribute = array( 'id'=>'register_form','form-horizontal'); ?>
<?php echo form_open('admin/products/add_product',$attribute); ?>
<?php echo form_label('product title'); ?>
<?php echo form_input($data_product_title); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product description'); ?>
<?php echo form_textarea($data_product_description); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product price'); ?>
<?php echo form_input($data_product_price); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product quantity'); ?>
<?php echo form_input($data_product_quantity); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_submit($data_3); ?>
<?php echo form_close(); ?>
Hope this will help you :
Your ajax script should be like this : , make sure your URL is correct
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url : baseURL+"admin/Products/add_product",
type:'post',
data: postData,
success:function(data)
{
console.log(data);
}
});
evt.preventDefault();
});
});
In your add_product method get post values like this :
public function add_product()
{
print_r($this->input->post()); // to print all post values
exit;
}
For more : https://www.codeigniter.com/user_guide/libraries/input.html
`$('#add').click(function() {
var form_data = {
subject_name: $('#subject_name').val(),
section: $('#section').val(),
grade: $('#grade').val()enter code here
};
$.ajax({
url:"<?php echo site_url('ViewCourses/SavingData');?>",
type:'POST',
data: form_data,
success: function(msg) {
if (msg == 'Yes')
document.location.reload(true);
else if (msg == 'No')
document.location.reload(true);
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg+'</div>');
}
});
return false;
});`
add Its Button Id Pe Use Of Onclick Function For Submit values With Ajax
form_data All Form Fields Of the Form

I want to pass id from view to controller in Codeigniter using Ajax and Update a Dropdown Selection in DB

I wanted to pass ID of each row from table and pass it to controller using AJAX and wanted to update the Dropdown Selection of that row in DB.
The Selection what i make in Dropdown is passed to the controller but not sure how to update in DB based on its each row condition. A help would be much Appreciated!!!
Below is the Screenshot of my UI
Screen Shot with ID and Dropdown
View File
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr class="idrow">
<td id="tdname" ><!-- style="display:none;" --> <?php echo $r->id; ?></td>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
<td><button type="button" class="btn btn-sm btn-success emlbtn" > Reply to <?php $fname=explode(" ",$r->fullname); echo $fname[0]; ?></button>
AJAX Code
$(document).ready( function() {
$(".statusClass").change(function(event) {
event.preventDefault();
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $(this).val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
'id'
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
Update Function in Model
public function feedback_update($data){
$this->db->set($data);
$this->db->where("id", $old_id);
$this->db->update('feedback_table', $data);
}
First change your $data array() like this :
$data = array(
'data-user' => $r->id, //ID of the row
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
Your ajax should be like this way:
$(".statusClass").each(function(index, element) {
$(this).on('change', function(e) {
var id = $(this).data('user');
var status = $(this).val();
console.log(id);
console.log(status);
// your ajax stuff go as usual
});
});
Based on the question, I come up with this simple solution. To be able to get the id and pass it yo your ajax call, all you need is add data-id for example inside your <td> tag.
Take a closer look below
<td id="tdname" data-id="<?php echo $r->id ?>" ><?php echo $r->id; ?></td>
Now that we have the id value inside our data-id, we can now pass it using jquery like below
$(document).ready( function() {
$(".statusClass").change(function(event) {
event.preventDefault();
var id = $("#tdname").data("id");
var status = $(this).val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit/" + id,
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Lastly, add the $id param inside your controller.

cant load controller function when clicking tag a on ajax in codeigniter

I have problem with my ajax in CodeIgniter, I cannot load function even I clicks on my anchor tag.
my view :
<a id="delete_article" href="#" style="margin-top:0px"><span class="label label-danger">Delete</span></a>
my ajax function :
<script type="text/javascript">
$(document).ready(function() {
$("#delete_article").click(function(event) {
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/ui_controller/deletearticle/<?php echo $twid;?>/<?php echo $id_session; ?>",
success: function(res){
$('#list_article').load("<?php echo base_url(); ?>index.php/ui_controller/list_article_plain/<?php echo $uid; ?>");
}
});
});
});
</script>
my controller :
public function deletearticle($twid,$uid){
$this->ui_model->deletearticle($twid);
}
public function list_article_plain($uid){
$data['article'] = $this->ui_model->get_a_place_where_uid($uid);
$this->load->view('user/list_article.html' , $data);
}
my model :
public function deletearticle($twid){
$this->db->where('twid', $twid);
$this->db->delete('tempat_wisata');
}
Ajax is executed based on event, while PHP is the first to be executed.
Your 'url' in
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/ui_controller/deletearticle/<?php echo $twid;?>/<?php echo $id_session; ?>",
success: function(res){
$('#list_article').load("<?php echo base_url(); ?>index.php/ui_controller/list_article_plain/<?php echo $uid; ?>");
}
});
is invalid.
The server simply do not execute the php code in 'url'.

Returning just an array to the view target div using jquery AJAX in cakePHP 1.3

When using jQuery AJAX in cakePHP 1.3, the AJAX response includes the full layout rather than just the array with dataset from the model. How to I prevent this whole page from being rendered? I have tried to use $this->autoRender = false; and $this->layout = 'ajax', but this did not solve the problem. It actaully produced no response in the returned data.
My controller action is:
public function search() {
if (empty($this->data)) {
} else {
// $this->autoRender = false;
// $this->layout = 'ajax';
$request = $this->data;
$this->set('data', $this->Event->search($request['Event']['search']), 'host');
}
}
And my view is:
<!-- app/views/events/search.ctp -->
<h1>Corporate Events</h1>
<form method="post" action="search">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
<p><?php echo $html->link("Add Event", "/events/add"); ?>
<table>
<tr>
<th style='width:100px'>Id</th>
<th style='width:100px'>Title</th>
<th style='width:100px'>Host</th>
<th style='width:100px'>Description</th>
<th style='width:100px'>Action</th>
</tr>
<div id= "results"></div>
<?php foreach ($data as $event): ?>
<tr>
<td><?php echo $event['id']; ?></td>
<td>
<?php echo $html->link($event['event_title'],'/events/view/'.$event['id']);?>
</td>
<td><?php echo $event['host']; ?></td>
<td><?php echo $event['description']; ?></td>
<td>
<?php echo $html->link(
'Delete',
"/events/delete/{$event['id']}",
null,
'Are you sure?'
)?>
<?php echo $html->link('Edit', '/events/edit/'.$event['id']);?>
</td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
var data = {'data[Event][search]':searchString};
if(searchString) {
$.ajax({
type: "POST",
url: "/events/search",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
Thanks!
I don't understand your question well, but this will help you with displaying to your view without the layout being echoed wholly.
Put this on the javascript inside the view,
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
if(searchString) {
$.ajax({
url: "/events/search/" + searchString,
beforeSend: function() { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(data){ // this happens after we get results
$("#results").show();
$("#results").append(data);
}
});
}
return false;
});
});
</script>
Then use the code below for your controller,
public function search($data=null) {
$this->autoRender = false;
//your code here;
return $data;
}
I would recommend having another function do the results and rendering them. Make a function called update_results. Following examples assumes you have request handler and jquery in place.
Simple Example:
//Controller
function search()
{
//search filters
$locations = $this->Event->Location->find('list',array('order'=>'Location.name'));
//set vars for view
$this->set(compact( 'locations'));
}//search
function update_results()
{
//location filter
if(!empty($this->data['Event']['location_id']))
$conditions['Event.location_id']=$this->data['Event']['location_id'];
$results=$this->Event->find('all',array('conditions'=>$conditions,'limit'=>15));
//debug($conditions);
$this->set('results',$results);
}//update result
//Views
//search.ctp
<?php echo $form->create('Event',array('action'=>'search'));
echo $this->Form->input('Event.location_id', array('label'=>'Location','empty'=>TRUE));
echo $js->submit('Find Trainings', array('update' => '#trainingresults','url'=> array('controller'=>'events', 'action'=>'update_results')));
echo $form->end(); ?>
<?php
echo $html->div('trainingresults',null,array('id'=>'trainingresults'));
echo '</div>';
?>
//update_results.ctp
<?php
$timestamp=date('r');
echo "<h4>Search Results ($timestamp)</h4><br/>";
if(empty($results))
{
echo "<p class='well'><strong>No Trainings found. Try different search criteria.</strong></p>";
}
else
{
foreach($results as $display)
{
//Event Info
$location=$display['Location']['name'];
echo $location;
}//for
}//else
?>

Categories