AJAX response variable undefined - php

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]);
}

Related

Get date from datepicker using Ajax with Laravel controller

i want to get the datepicker value when user selected a date and send that using ajax to a laravel controller. this code is not worked for me..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#date').datepicker({
format: 'dd-mm-yyyy',
onSelect: function(date, instance) {
$.ajax({
type: "POST",
url: '/process_date',
data: date,
success: function(result)
{
console.log(result);
}
});
}
});
here is my route,
Route::post('/process_date', 'TimeController#ajaxTime');
here is my controller,
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
Try changing your code to this because I have been reading the documentation and testing it with some code of my own and this is what I came up with
$('#date').datepicker({
format: 'dd-mm-yyyy',
}).on('changeDate', function(e) {
$.ajax({
type: "POST",
url: '/process_date',
data: {
date: e.date.toString(),
},
success: function(result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
})
and also change your TimeController class from
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
to
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
return $request->all(); // This will get all the request data.
}
}
to receive better results in your browser console.

Pass a View Data From Controller to Ajax View File - Laravel 5

From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}

Doesn't work AJAX in Laravel 5.4

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

how to return json response in laravel

this is my controller:
public function index(Request $request)
{
$items = Post::latest()->paginate(5);
$cmnt = Comment::all();
return response()->json(array('posts'=>$items,'comment'=>$cmnt));
}
this my ajax request
function getPageData() {
$.ajax({
dataType: 'json',
url: "{{route('post_status.index')}}",
data: {page:1}
}).done(function(data){
manageRow(data.data);
});
}
function manageRow(data) {
console.log(data.comment);
}
why i am getting error ??
help me out of this plzz
laravel returns json by default if it doesn't return view, in your case index() should return:
return ['posts' => $items,'comment' => $cmnt];
also I don't think this is correct
{{route('post_status.index')}}
probably should be
{{ url('post_status/index') }}
You can use the type of response from the server.
function getPageData() {
$.ajax({
dataType: 'json',
url: "{{route('post_status.index')}}",
type: 'GET'
data: {page:1}
}).done(function(data){
manageRow(data.data);
});
}
function manageRow(data) {
console.log(data.comment);
}

Reading a very simple ajax request in Laravel

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');

Categories