I have list of records. I want to delete a record by clicking on it, but when I use this $.ajax() function it removes the row but does not delete from the database.
html code
<tbody>
<tr class="gradeX odd">
<td class="sorting_1">2</td>
<td class=" ">test</td>
<td class=" ">test</td>
<td class="center ">0</td>
<td class="center ">Active</td>
<td class=" "><button type="button" class="btn btn-default btn-circle" name="editRecord"><i class="fa fa-pencil-square-o"></i></button>
<button type="button" class="btn btn-danger btn-default btn-circle" id="2" name="deleteRecord"><i class="fa fa-times"></i></button></td>
</tr>
<tr class="gradeX even">
<td class="sorting_1">3</td>
<td class=" ">sarees</td>
<td class=" ">contains sarres</td>
<td cl="center ">1</td>
<td class="center ">Active</td>
<td class=" "><button type="button" class="btn btn-default btn-circle" name="editRecord"><i class="fa fa-pencil-square-o"></i></button>
<button type="button" class="btn btn-danger btn-default btn-circle" id="3" name="deleteRecord"><i class="fa fa-times"></i></button></td>
</tr>
</tbody>
jquery
$(document.body).on('click', '[name="deleteRecord"]', function(){
var id= $(this).attr('id');
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "admin_operation.php?mode=delete_category",
data: data,
cache: false,
success: function(data)
{
console.log(data);
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
php code
$mode = $_GET['mode'];
if($mode=='delete_category')
{
$id=$_POST['id'];
$q=$db->query("DELETE FROM db_category WHERE category_id='".$id."'");
if($q){ echo "yes";}
else{ echo "no";}
}
Ajax(mode and id as get vars):
$.ajax(
{
type: "GET",
url: "admin_operation.php?mode=delete_category&id="+id,
cache: false,
success: function(data)
{
console.log(data);
parent.fadeOut('slow', function() {$(this).remove();});
}
});
Php:
$mode = $_GET['mode'];
if($mode=='delete_category')
{
$id=$_GET['id'];
$q=$db->query("DELETE FROM db_category WHERE category_id='".$id."'");
if($q)
{ echo "yes";
}
else
{ echo "no";
}
}
Send the parameter "mode" with the variable "data" and only use $ _POST to retrieve the values. Thus the parameter "URL" will only have the value "admin_operation.php" and the variable "data" will contain:
var data = 'id =' + id + '&mode=delete_category';
Example:
var id = $(this).attr('id');
var data = 'id=' + id + '&mode=delete_category';
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "admin_operation.php",
data: data,
cache: false,
success: function(data)
{
console.log(data);
parent.fadeOut('slow', function() {$(this).remove();});
}
});
You are telling PHP to get parameters both from GET and POST. Your form is sending as GET. So as it is, your code is not executing the SQL statement because $id is blank.
You need to change it to only use GET since that's what you are sending on your form.
$id=$_GET['id'];
Also, your Javascript is removing the line because you are not validating on the server if the line was removed or not. Make sure you check that.
$.ajax(
{
type: "GET",
url: "admin_operation.php?mode=delete_category",
data: data,
cache: false,
success: function(data)
{
console.log(data);
parent.fadeOut('slow', function() {$(this).remove();});
}
});
Related
I want to display pdf icon only when the field (WO_doc) is not empty. I don't know what I am doing wrong while writing the if statement. Please help.
<script type="text/javascript">
$( "select[name='PEF_id']").change(function () {
var Pefid = $(this).val();
if(Pefid) {
$.ajax({
url: "<?php echo site_url('Admin/showwo');?>",
dataType: 'Json',
data: {'PEF_id': Pefid},
success: function(response){
$(".displayNone").removeClass("displayNone").addClass("displayHidden");
$.each(response.wo,function(key, value) {
$('.wodata').append('<tr>\
<td>'+value['WO_no']+'</td>\
<td>'+value['WO_date']+'</td>\
<td>'+value['Agency_name']+'</td>\
<td>'+value['WO_amount']+'</td>\
<?php if("?>'+value['WO_doc']+'<?php" != null) { ?>\ ***this if condition is not working***
<td></i></td> <?php } else { ?> <td></td> <?php } ?>\
<td><button type="submit" name="submit" class="btn btn-success">Update</button></td>\
<td><button type="submit" name="submit" value="'+value['WO_no']+'" class="button-del btn btn-danger">Close this WO</button></td>\
</tr>');
});
}
});
}
});
</script>
Please I need help to figure out why my code below isn't working. I'm not very good at PHP and ajax to start with but find it difficult to figure out why the code below wouldn't function properly.
What it does: changes data in database to 'Disable' but to update to 'Enable' on-click wouldn't work. Please help!
status.php
<?php
session_start();
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="User"){
header('location:index.php');
}
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
if (isset($_POST['ridd'])){
$id=$_POST['ridd'];
if($row->user_status == 'Enable'){
$status_str="Disable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str, $id]);
}else if($row->user_status == 'Disable'){
$status_str2="Enable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str2, $id]);
}else{
echo'Internal loop error in Updating';
}
}
}
registration.php
<script>
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id
},
success: function(data) {
//tdh.parents('tr').load;
}
});
swal("User status has been changed!", {icon: "success",});
window.location.reload(true);
} else {
swal("No action performed!");
window.location.reload(true);
}
});
});
});
</script>
here is my table code in registration.php
<tbody>
<?php
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
$status='Disable';
$colour="btn-danger";
if($row->user_status == 'Enable'){
$status='Enable';
$colour="btn-success";
}
echo'
<tr>
<td>'.$row->userid.'</td>
<td>'.$row->username.'</td>
<td>'.$row->user_status.'</td>
<td>
<div id='.$row->userid.' class="switch">
<button type="button" class="btn '.$colour.'">'.$status.'</button>
</div>
</td>
<td>
<button id='.$row->userid.' class="btn btn-danger btndelete" ><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
';
}
?>
</tbody>
When I click on button 'switch', I'm able to perform a toggle function so that it can update either 'Enable' or 'Disable' on my database. At the moment, only the disable is working and I have to manually enable the user from the database (phpmyadmin).
You can check if the button which is clicked has class btn-success if yes then now we need disable it or else enable so send this as well in your ajax call and at your backend get it using $_POST["status"] and update same . Also, you don't need to reload page instead inside your success function of ajax just change the button using .html().
Demo code :
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
var button_status = $(this).find("button").hasClass("btn-success") ? "Disable" : "Enable"; //check if button has success means we need disable it now else enable .
/*$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id,
status: button_status //send to chnage
},
success: function(data) {*/
//if disable
if (button_status == "Disable") {
$("#" + id).html("<button type='button' class='btn btn-danger '>Disable</button>") //put enable button
tdh.closest("tr").find("td:eq(2)").text("Disable")
} else {
$("#" + id).html("<button type='button' class='btn btn-success '>Enable</button>") //disable buttn
tdh.closest("tr").find("td:eq(2)").text("Enable")
}
/* }
});*/
swal("User status has been changed!", {
icon: "success",
});
} else {
swal("No action performed!");
}
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
<table class="table">
<tbody>
<tr>
<td>1</td>
<td>sw</td>
<td>Enable</td>
<td>
<div id='1' class="switch">
<button type="button" class="btn btn-success ">Enable</button>
</div>
</td>
<td>
<button id='1' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
<tr>
<td>2</td>
<td>sw</td>
<td>Disable</td>
<td>
<div id='2' class="switch">
<button type="button" class="btn btn-danger ">Disable</button>
</div>
</td>
<td>
<button id='2' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
</tbody>
</table>
I'm working on a project with codeigniter and I decided to implement ajax into the comment section so that the whole page is not refreshed when the user submits his comment. The comment is displayed automatically but the page keeps getting refreshed. I don't know what I am doing wrong here but any help would be appreciated.
MODEL:
public function create_comments($post_id){
$data = array(
'post_id' => $post_id,
'body' => $this->input->post('body'),
'users_id' => $this->session->userdata('user_id')
);
return $this->db->insert('comments',$data);
}
CONTROLLER:
public function create($post_id){
//checking if user is logged in
if(!$this->session->userdata('isLoggedIn')){
redirect('users/login');
}
$slug = $this->input->post('slug');
$data['post'] = $this->post_model->get_posts($slug);
$this->form_validation-> set_rules('body', 'Comment', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
$this->session->set_flashdata('comment_error', 'comment field is empty comment');
redirect('posts/'.$slug,'refresh');
} else {
$this->comments_model->create_comments($post_id);
redirect('posts/'.$slug);
}
}
VIEW:
<?php echo form_open_multipart('comments/create/'.$post['id'], 'id="comnt"'); ?>
<div class="panel-footer">
<!--//THIS IS THE FIELD WHICH COMMENTS WOULD BE ADDED-->
<div class="">
<input type="hidden" name="slug" value="<?php echo $post['slug']; ?>">
<small class="text-center text-danger"><?php echo form_error('body'); ?></small>
<div class="input-field">
<textarea id="icon_prefix2" name="body" class="materialize-textarea" rows="3"></textarea>
<label for="icon_prefix2">Comments</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" id="submit">comment <i class="material-icons right">send</i></button>
</div>
</div>
</form>
AJAX:
$('#submit').click(function() {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Use jquery preventDefault() function to prevent your form to be submitted
$('#submit').click(function(e) {
e.preventDefault();
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>"+"comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Try the done property to set the success handler. Also, as this is an event over a DOM element, you should attach it when the DOM is ready:
$(document).ready(function() {
$('#submit').click(function(event) {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
}).done(function(msg) {
alert(msg);
}).fail(jqXHR, textStatus) {
alert('ERROR: ' + textStatus);
});
// return is not necessary here
// return true;
});
$("#comnt").submit(function(e) { // Prevent the form submitting
e.preventDefault();
});
});
As this already attaches an event, you should remove the onclick="comment()" property from your button:
<button class="btn waves-effect waves-light" type="submit" id="submit">comment
<i class="material-icons right">send</i>
</button>
Try this hope it work
$('#submit').click(function(event) {
e.preventDefault(); //stop actual action of browser
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Change button type button instead of submit
<button class="btn waves-effect waves-light" type="button" name="action" id="submit">comment
<i class="material-icons right">send</i>
</button>
passing data to controller using AJAX
this is script i have written to pass data to controller but data is not passed to the controller
this is the input data i want to pass
<div class="form-group">
<table class="table table-striped b-t b-light text-sm">
<thead>
<tr>
<th>ID</th>
<th>Question</th>
<th>answer</th>
</tr>
</thead>
<tbody>
<?php foreach ($quet as $row) { ?>
<tr>
<td ><?php echo $row['id']; ?></td>
<td>
<?php echo $row['question']; ?>
</td>
<td><input type='text' name='name' required="required" class="form-control" placeholder='Enter Your Answer'></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" id ="next" type="button" >Next</button>
and the script
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("name").val()
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/student/add",
data: 'data='+array,
contentType:'application/json',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
and the student controller
function add(){
if($this->student_model->add($this->input->post()))
{
$response['success'] = TRUE;
}
else
{
$response['success'] = FALSE;
}
echo json_encode($response);
}
Try this. Your data may be in wrong format
data: {'data':array}
EDIT
<input type='text' name='answer' id='answer' required="required" class="form-control" placeholder='Enter Your Answer' />
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("#answer").val() // see the change name to id, see the html also
$.ajax({
type: "POST",
url: BASE_URL+"/student/add",
data:{'data':array},
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
});
});
</script>
Also check the array is received properly in you JS
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("#id").val()
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/student/add",
data: {
'data':array
},
contentType:'application/json',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
In your controller you should change $this->input->post() to$this->input->post('data')
From your mentioned code, you need to check these points :
1) As you are using contentType:'application/json', so use the data format as data: {'data':array}
2) Finally check whether the url url: BASE_URL+"/student/add", is accessible or not.
Hope this helps :)
You need to change following in your code.
In the Script
<script>
$(document).ready(function($){
$("#next").click(function(){
var array = $("input[name]").val();
$.ajax({
type: "POST",
url: BASE_URL+"/student/add",
data: {'data':array},
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
},
datatype:"json"
});
return false;
});
});
</script>
In the Student Controller
function add(){
if($this->student_model->add($this->input->post('data')))
{
$response['success'] = TRUE;
}
else
{
$response['success'] = FALSE;
}
echo json_encode($response);
}
I hope this help.
<?php $count = 1; foreach ($settings[$slug] as $slug): ?>
<div data-toggle="buttons-radio" class="btn-group">
<button id="enable" value="1" class="btn btn-success active" type="button" name="includeicon"><i class="icon-ok icon-white"></i></button>
<button id="disable" value="0" class="btn" type="button" name="includeicon"><i class="icon-remove"></i></button>
</div>
<?phpendforeach?>
$(document).ready(function(){
$("#enable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/PluginConf/enable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
$("#disable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/PluginConf/disable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
});
I am passing button id in jquery, but ajax is getting called only for first button. For second and others it is not getting called, can anyone help me out in this?
Thanks
You have an id of enable and disable in a foreach. If the loop ever executes more than once you will then have multiple buttons with the same id. IDs have to be unique! Rather use something else to identify the click:
I suggest adding an enable class to the enable button and a disable class to the disable button, then catch the events like this:
$('.enable').click(function() {
// code in here
});
$('.disable').click(function() {
// code in here
});
Don't bind the click event(s) for multiple items by id! Ids have to be unique idetifiers.
<?php $count = 1; foreach ($settings[$slug] as $slug): ?>
<div data-toggle="buttons-radio" class="btn-group">
<button value="1" class="enable btn btn-success active" type="button" name="includeicon"><i class="icon-ok icon-white"></i></button>
<button value="0" class="btn disable" type="button" name="includeicon"><i class="icon-remove"></i></button>
</div>
<?phpendforeach?>
$(document).ready(function(){
$(".enable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/enable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
$(".disable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/disable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
});
You are using id what is not correct when several elements in your case buttons have the same id.When you use foreach loop you create multiple buttons with the same particular id. ID means that something is unique, and only one element can have that specyfic id. I assume you should make a class for this buttons and change your script code with having this in mind. Here what I suggest. Hope it helps.
<?php $count = 1; foreach ($settings[$slug] as $slug): ?>
<div data-toggle="buttons-radio" class="btn-group">
<button value="1" class="btn btn-success active enable" type="button" name="includeicon"><i class="icon-ok icon-white"></i></button>
<button value="0" class="btn disable" type="button" name="includeicon"><i class="icon-remove"></i></button>
</div>
<?php endforeach; ?>
$(document).ready(function(){
$(".enable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/enable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
$(".disable").click(function(event) {
var slugid = $('#slugid').val();
$.ajax({
url: SITE_URL + 'admin/xervPluginConf/disable/?'+slugid,
type: "POST",
data : {'slugid' : slugid},
success: function(data) {
}
});
});
});