could You, please, help me? My code is dorsn't work. JS alert 'succes' but it's no changes on page. Thank You
Route
Route::post('/more', 'IndexController#index');
jQuery
$('#moreBtn').click(function () {
$.ajax({
method: 'post',
url: '/more',
data: 'fas',
async: true,
success: function(){
alert('succes');
},
error: function(data){
console.log(data);
alert("fail" + ' ' + this.data)
},
});
});
Controller
class IndexController extends Controller
{
public function index(Request $request)
{
$count = 8;
$videos = Video::leftJoin('users', 'videos.user_id', '=', 'users.id')
->select('users.id', 'users.name', 'videos.*')
->orderBy('created_at', 'desc')
->take($count)
->get();
if ($request->ajax()) {
$count += 4;
}
return view('welcome', array(
'videos' => $videos
));
}
}
Like i said, it's return 'succes', like ajax is ok, but doesn't change my page.
Data is not changing , because you are not changing it.
Your ajax should more like
$.ajax({
method: 'post',
url: '/more',
data: 'fas',
async: true,
success: function(response){
alert('succes');
$('body').html(response) // or to the id/class you would like to change
},
error: function(data){
console.log(data);
alert("fail" + ' ' + this.data)
},
});
And one more thing, when you are doing ajax post request it is a good practice too keep and pass the token with the dat
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");
}
});
}
In my app i want to pass the id one by one form view to controller using jquery and sum there value
and print in view
how can i do that any body help
expected result is 25 not 13 in total price
this is the view
http://prntscr.com/nam2nb
this is my controller
public function price_count(Request $request)
{
$total_parice = DB::table('tms_store')
->where('product_id', $request->id)
->select(DB::raw('sum(product_price) as total_amount'))
->first();
Session::put('price', $total_parice);
$price = Session::get('price');
return response()->json($price);
}
this is jquery
function total_amount(id)
{
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: APP_URL+"/driver-equipment/price",
type: 'POST',
dataType: 'json',
data: {_token: CSRF_TOKEN,'id' : id},
})
.done(function(res) {
console.log(res)
$("#totalPrice").val(res.total_amount);
})
.fail(function() {
console.log("error");
})
}
You can just do this :
$total_amount = DB::table('tms_store')
->where('product_id', $request->id)->sum('product_price');
I have made a AJAX request and trying to show the result as HTML.
My controller:
public function searchByRange(Request $request)
{
$query = DB::table('visitors')
->where('id','=',$request->id)
->where('visitors.user_id','=',Auth::user()->id)
->whereBetween('visitors.created_at', array($request->first_date, $request->second_date) );
$visitors = $query->get();
return view('analytics.analytics-range',['visitors' => $visitors]);
}
My AJAX part:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: "{{url('searchByRange')}}",
dataType: 'html',
data:
{
first_date : first_date,
second_date : second_date,
id : id
},
success: function(html)
{
$(".date-range").html(html)
}
});
But the problem is ajax response in console is
ErrorException (E_ERROR) Undefined variable: visitors
What could be possible error for that?
try changing your controller function to:
public function searchByRange(Request $request)
{
$visitors = DB::table('visitors')
->where('id','=',$request->id)
->where('visitors.user_id','=',Auth::user()->id)
->whereBetween('visitors.created_at', array($request->first_date, $request->second_date))
->get();
return view('analytics.analytics-range',['visitors' => $visitors]);
}
I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $data]);
I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');