I am working on a project, where inside admin panel I have a table for enquiries and I want to allow admin to delete any of them.
My view code is as follows:
<button type="button" class="btn btn-danger delbtn" onclick="delenquiry(<?php echo $value->id;?>)">Delete this Enquiry</button>
My ajax code is:
function delenquiry(id) {
if (confirm("Are you sure?")) {
$.ajax({
url: base_url + 'loginc/delenq',
type: 'post',
data: id,
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
} else {
alert(id + " not deleted");
}
}
Controller code is:
public function delenq() {
$id = $this->input->post('id');
$this->logins->delenqs($id);
}
And model code is:
public function delenqs($id) {
$this->db->where('id', $id);
$this->db->delete('enquiry');
}
I looked for answers, but didn't got any. Can anyone tell me what's wrong with my code. Thanks in advance...
You need to pass id from your ajax request change
data: id,
To
data: {id:id},
for data you must provide an array .
for example => data:{name_params:10}
you can get data in php $id = $this->input->post('name_params');
and the value $id will be = 10
The issue you have is that your ID is not an available key in your POST. You would need to define {id : id}. However, I think this makes more sense from an MVC approach:
$.ajax({
url: base_url + 'loginc/delenq/'+ id, //maintains the (controller/function/argument) logic in the MVC pattern
type: 'post',
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a,b,c);
}
});
Then you can expect an argument to your controller function:
public function delenq($id){
if($id)
return $this->logins->delenqs($id);
return false;
}
And finally, your model can get a little fixer upper so that it properly returns as well.
public function delenqs($id) {
$this->db->delete('enquiry', array('id' => $id));
return $this->db->affected_rows() > 1 ? true:false;
}
Related
I am working with Laravel Datatable and I have stuck in one point. Below code for delete the entry in the TagManagement model. But it isn't delete the entry and worse thing is it didn't show any error. Can anybody find the error in below code?
view
$(document.body).on("click",".remove-tag", function () {
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
Controller
public function destroy($id)
{
$tagManagement = TagManagement::find($id);
$deleted = $tagManagement->delete();
if ($deleted) {
return "SUCCESS";
} else {
return "FAIL";
}
}
public function loadTags()
{
$Tags = TagManagement::all();
return DataTables::of($Tags)
->addColumn('action', function ($tag) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $tag->id . '" class="btn btn-default remove-tag remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
}
**Route**
Route::get('/delete-tag', 'AdminPanel\TagController#destroy');
Your route and controller method don't seem to correspond. First of all, it is better to use the "delete" HTTP request method for delete actions, but this is not what is causing your problem.
You defined your route as /delete-tag but in your controller you expect an $id as a parameter to your destroy method. In order for that to work you would need to have the route like this /delete-tag/{id} and construct the URL for your ajax call correspondingly on the frontend. I'm surprised you don't get the Missing argument 1 for App\Providers\RouteServiceProvider::{closure}() exception for malforming your request this way.
Laravel documentation explains very well how to define routes with parameters.
It would be helpful if you included Laravel version in your question.
Here is how it should work:
Route definition
Route::delete('/delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('delete-tag');
JS function
function deleteTag(id){
let route = '{!! route('delete-tag', ['id' => '%id%']) !!}';
$.ajax({
type: 'post',
url: route.replace('%id%', id);,
data: {_method: 'delete'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
It is not your Datatable problem, you missed some code, you did not define route & jQuery function properly, your destroy($id) function received a parameter but you do not receive any parameter in your route & you not send _token in your ajax action you need to send _token
Check My code I am edited your code.
//Change your Route
Route::get('delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('deleteTag');
//Change your function
function deleteTag(id){
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('deleteTag', '') }}/'+id,
data: {_token: '{{csrf_token()}}'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
i have an array like
[{"id_pelanggan":"1","id_tipe":"5","nama_pelanggan":"ASD","alamat_jalan":"DS","alamat_kota":"1","alamat_provinsi":"ATA","kontak_pelanggan":"45454"}]
and my ajax
$(function() {
$("#autocomplete").change(function(){
var namaagen = $("#autocomplete").val();
$.ajax({
url: '<?php echo site_url('Pelanggan/tampil_where'); ?>',
type: 'POST',
dataType: 'json',
data: {
'namaagen': namaagen
},
success: function (agen) {
$("#napem").val(agen['nama_pelanggan']);
}
});
});
});
});
});
controller :
public function tampil_where(){
$nama = $this->input->post('namaagen');
$query = $this->pelanggan_m->tampilwhere($nama);
echo json_encode($query);}
models:
public function tampilwhere($nama){
$this->db->select('*');
$this->db->from('nm_pelanggan');
$this->db->where('nama_pelanggan',$nama);
$this->db->order_by('id_pelanggan', 'ASC');
$query = $this->db->get()->result_array();
return $query;
}
but nothing happen and i already add alert(agen['nama_pelanggan']); in response success and show alert undefined pls help , thanks for advance
Please change your alert code, right now you don't access response array in the proper way:-
alert(agen[0]['nama_pelanggan']);
Instead of:-
alert(agen['nama_pelanggan']);
Thanks
i am having trouble in concating the value of my two ID's from database to generate a new ID and use it to save again in Database. I am using codeigniter and i want something a good technique/way to concat for better result or maybe faster.
Also i am having a problem, whenever there is a value in my database, i cannot increment my ID by having +1. I got an output of 1-undefine-1
Here is my ajax:
function getcheckupID() {
var init = 0;
var value = $('#clinicID').html();
$.ajax ({
url: siteurl+"myclinic/getcheckID",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
$('#checkID').text(value+"-"+data[0]['clinic_id']+1);
$("#checkID").css('visibility','visible');
}
else {
$('#checkID').text(value+"-"+init);
$("#checkID").css('visibility','visible');
}
}
})
}
function get_clinicID() {
$("#clinicID").empty();
$.ajax({
url: siteurl+"myclinic/get_clinicID",
type: "GET",
dataType: "JSON",
success: function(data) {
$('#clinicID').text(data[0]['clinic_id']);
}
});
}
i check the records in my DB using this if(data.length>0) then if i got record, i go get the data and +1 it. I got a value of undefined, but if it goes to else, it outputs bad, because whenever i refresh it. sometimes it only outputs - 0, where i want is 1-0. Then refresh it again. How can i concat safely ? Is it an issue in ajax ?. making slow ?
Here is my controller for it :
public function getcheckID() {
$checkID = $this->clinic_model->checkupID();
echo json_encode($checkID);
}
My Model :
public function checkupID() {
$query = $this->db->query('SELECT tbl_check_up.check_up_id FROM tbl_check_up');
return $query->result();
}
I'm using Yii 2.0 basic version and I need some help.
I created one ajax function like this:
function eliminarColaborador(id) {
$.ajax({
type: "GET",
async: false,
url: "<?= urldecode(Url::toRoute(['colaborador/ajaxEliminarColaborador'])) ?>",
dataType: 'json',
data: {
'id': id
},
complete: function ()
{
},
success: function (data) {
if (data !== null)
{
// SUCCESS
}
else
{
// ERROR
}
}
});
}
My action in controller:
public function actionAjaxEliminarColaborador($id) {
if (Yii::$app->request->isAjax) {
$continuar = false;
if(isset($id) && $id > 0) {
var_dump($model); die;
$continuar = true;
}
echo CJSON::encode(array('continuar'=>$continuar));
Yii::$app->end();
}
}
I'm getting this erro in firebug: Not Found (#404): Page not found.
I tried everything, but i can't figure out what's the problem.
If I change ajax url to urldecode(Url::toRoute(['colaborador/delete'])) the error is gone and all works just fine.
Maybe I need to declare in ColaboradorController my new action ajaxEliminarColaborador, but I don't know how.
What is wrong?
controller
public function actionAjaxEliminarColaborador(){}
ajax
urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador']))
It should be <?= urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador'])) ?>. Here you can learn why.
Change the ajax response with:
url: '/colaborador/ajaxEliminarColaborador/$id',
data: {id: $id,_csrf: yii.getCsrfToken()},
Try to remove the word 'ajax' on your url.
I am doing a delete on a table using jquery,
$('table#chkbox td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: { 'id': id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
I am getting the id value correctly but my data parameter doesn't get passed to my controller,
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Any suggestion...
I am getting the error,
Missing argument 1 for libraryController::librarydelete() and Undefined variable: id
Your are posting the data, so you can get the id like this:
function librarydelete()
{
$del = $_POST['id'];
echo $del;
$this->librarymodel->deletebook_issue($_POST['id']);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Looks like you are using codeigniter, so this would be even better:
$del = $this->input->post('id');
Change id to $id in controller function parameter
means, your function should be
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Perhaps it is because you are using the variable name 'data' twice. Try renaming var data to var mydata.
The way you are passing data is wrong. This is the way you should be setting data.
var data= {id: id };
in your case let me not use the variable in the post action and show you how its done.
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
Edit: After you modified your code to pass data the right way.
Hey I have not followed MVC framwework in php. but since you are doing a post on the action you can always get the data the following way:
$id=$_POST['id']
and then you can use this id.
Also if you still want to use the function:
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
just modify the uri action to existingurl+/ i.e append the id to the end and in your route map (if there exists something like this in php in .nets implementation there is 1) just add that route.