Laravel 5.7 9 Yajra Datatable delete button - ajax

My button in the table is created by:
return Datatables::of($members)
->addColumn('action', function ($id) {
return 'Edit
<button class="btn btn-primary btn-delete" data-remote="/admin/members/' . $id->id . '">Delete</button>
'; })->make(true);
The js function:
$('#datatable-member').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
alert(url);
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#datatable-member').DataTable().draw(false);
});
});
the return of the debugging alert is (for example): /admin/members/2
The route is this one:
DELETE | admin/members/{member} | members.destroy | App\Http\Controllers\Admin\MemberController#destroy | web
I have this error in the JS console:
jquery-3.3.1.min.js:2 DELETE http://127.0.0.1:8000/admin/members/2 404 (Not Found)
...and of course, the delete doesn't work...

Related

Yii2, send AJAX request with link

I need to send AJAX request using link.
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
May be construction like this?
<?php
$js = <<<JS
$(".messages_close").click(function () {
var id = 8;
$.ajax({
url: "'.\yii\helpers\Url::toRoute(['messages/exclude','id'=>8]).'",
type: "get",
data: "id="+this.id,
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR :: ' + 'id=' + this.id);
}
});
});
JS;
$this->registerJs($js);
Is it possible? Thank you
UPDATE 1
Thanks for #vvpanchev and #Serghei Leonenco
I did some changes:
added use yii\helpers\Url and changed url:;
removed data: "id="+this.id
removed var id = 8 it used in URL
I still get ERROR alert! ((
How can I get SUCCESS, or better return message from controller?
Here is my code looks like:
view\messages.php
<?php
use yii\helpers\Url;
?>
...
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
...
<?php
$js = <<<JS
$(".messages_close").click(function () {
$.ajax({
url: "' . Url::toRoute(['messages/exclude','id'=>8]) . '",
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
MessageController.php (it opens in browser without problem)
<?php
namespace app\controllers;
use Yii;
use app\models\MessagesUsers;
use yii\web\Controller;
class MessagesController extends Controller
{
public function actionExclude($id)
{
return 'Success ID=' . $id;
}
}
Thank you for your help!
SOLUTION
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);

how to make successfull ajax success

Button code
this is my button code with id 123
<button type="submit" class="addto" id="123">Add to cart</button>
ajax code
This is my ajax code
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
$id=this.id;
//alert($id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test', //route url
dataType:"json",
type:"POST",
data:{id:this.id},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
Route code
this is my route code
Route::match(['get','post'],'/test','ajaxcontrol#test'); //route url
Controller code:
How to solve this, i have included all the imports
class ajaxcontrol extends Controller
{
public function test(Request $request){
$valu=$request->id;
echo json_encode($valu);
}
}
Try to change your ajax like this:
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
id=this.id;
//console.log(id);
$.ajax({
url: "{{ url('/test') }}", //route url
dataType:"json",
type:"POST",
data:{
id:id,
"_token": "{{ csrf_token() }}",
},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});

How to reload the part of table?

I have this table:
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data("id");
$.ajax(
{
url: "client/"+id,
type: 'delete',
dataType: "JSON",
data: {
"id": id
},
success: function (response)
{
$("#reload_table").load(window.location + " #reload_table");
}
});
});
Simply after delete first one test2 everything is good and reload the part of table, but when I go to delete test1 it does not delete it, I have to reload the whole page then delete it!
I'm use this for reload the table but it reload for just one time!:
$("#reload_table").load(window.location + " #reload_table");
How can I make it reload table ?
I'm not using any library like datatable etc, it just simple bootstrap table.
Alternative : Remove tr after ajax success
#forelse($users as $user)
//...
<tr id="{{ $user->id }}">...</tr>
//...
#empty
<p>No data Available</p>
#endforelse
//js
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data("id");
$.ajax(
{
url: "client/"+id,
type: 'delete',
dataType: "JSON",
data: {
"id": id
},
success: function (response)
{
$('#'+id).remove();
}
});
});
Since you are binding the event to an element inside the table row, you should be able to simply delete the table row by finding the closest tr to that element:
$(this).closest('tr').remove();

Ajax page is reloading after storing data

i am triyng to save data but my page is reloading with json message on next page, how can i stop reloading page.
Ajax Code:
jQuery(document).ready(function($) {
$("#add-data").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Submit Button:
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
Store Controller:
after saving which is working fine:
return response()->json([
'status' => 'success',
'msg' => 'New esecond has been saved'
]);
It is because of you are trying to post the data to form .
If you use button type = "submit" it will redirect you to somewhere .
You should avoid using type = "submit" .
Instead use the type = "button"
<button type = "button" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
And achieve it by using click event of the button .
then get it in jquery .
$("#add-data").click(function (event) {
//Your code here
}
You can try this instead of prevent default. The reload happen, because you use form submit event.
$('#add-data').submit(false);
If you want to use prevent default, then use click event of the submit button to perform the action.
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
}
Remove dataType: 'json' as you're already returning JSON otherwise your button seems perfect.
Try this
jQuery(document).ready(function($) {
$("#add-data").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Add "return false;" in the end of your submit callback..
As "add-data" is ID of your button, for your example it couldn't retrieve a submit event. That's because it submitted and didn't prevented.
So you can write something like this:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({ ... });
return false; // <<< THE THING
});
Or just do that with binding an click event on button (not for submit event on button)
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({ ... });
});
With this you can leave button type, and don't need to change that to type="button".

Laravel : can't read data from my Ajax jQuery code in my controller

i'm sending the section id in my ajax function,but i can't receive this data in my controller function.need your help please.
This is my jQuery:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
},
success: function(){
alert(section);
},
error: function(){
alert("error");
}
});
$.post("{{URL::to('/ajax')}} ",function(data){
$('#groupe').empty().html(data);
});
});
});
Web:
Route::post('ajax' , 'SeanceController#ajaxfct');
My function in the controller:
public function ajaxfct(Request $request){
$id = $request->section;
$groupes = \DB::table('groupes')
->where('section_id','=',$id)
->get();
return view('seance.groupe')->with([
'groupes' => $groupes
]);
}
The code is close to working perfectly, the following setup passes the data correctly:
HTML:
<select id="getGroupe">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
}
}).done(function( msg ) {
console.log('response: ', msg)
});
});
});
</script>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeanceController
{
public function ajaxfct(Request $request)
{
return ['received' => $request->section];
}
}
Route:
Route::post('/ajax', 'SeanceController#ajaxfct');

Resources