Get date from datepicker using Ajax with Laravel controller - php

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.

Related

AJAX response variable undefined

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

Can't call a custom method on a controller from AJAX

I am trying to call a controller function from an AJAX call. The view loads from the same controller, but I'm not able to call the function.
Here is the controller code:
// This function will get ajax call where pass two variables and a method name doSomeAction
class Posts extends \Core\Controller
{
public function addNewAction()
{
View::renderTemplate('Posts/addnew.html', [
// 'posts' => $posts
]);
}
public function doSomeAction()
{
echo "here";
// your action code ....
}
}
Here is my Ajax script call function
<script>
$(".submitcontr").click(function() {
$.ajax({
url: 'POST/doSomeAction',
dataType: 'json',
data: {
id: 'value'
},
success: function (data) {
console.log(data);
},
error: function () {
alert('error');
}
});
});
</script>

Laravel/ajax retrieving data from database

I use laravel and now I want to search from DB by ajax. It work but I want to show the result any where that I want not in the footer in current situation.
Do you now how get and show data in this section?
<script>
$(document).ready(function() {
src = "{{ url('/')}}/users/searchhistory";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 1,
});
});
</script>
And controller
public function autoComplete(Request $request) {
$query = $request->get('term','');
$products=User::where('fullname','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($products as $product) {
$data[]=array('value'=>$product->fullname,'id'=>$product->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
use json() in return statment of controller
public function autoComplete(Request $request)
{
//othercodes
return response()->json($data);
}
Then in your ajax result you have the proper json-formatted response
You can add data to html tag
$.ajax({
success: function(data) {
$.each(data,function(prodcut){
// now you have every product
use javascript append function to a add new element with this product data
});
}
});

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

Laravel 5 - AJAX not working

I have one problem with my script on LARAVEL 5. This is my route:
Route::get('cms/section/addCategory', 'Cms\SectionController#showCategory');
Route::post('cms/section/addCategory', 'Cms\SectionController#addCategory');
Controller:
// SHOW FORM WITH ADD CATEGORY
public function showCategory()
{
if (Sentinel::hasAnyAccess(['section.create']))
{
return view('cms.viewSystem.section.addCategory');
}
else
{
return view('cms.viewSystem.error');
}
}
// ADD NEW CATEGORY
public function addCategory()
{
return http_response_code(200);
}
Ajax Script:
$(document).ready(function() {
$('form.ajax input[type=submit]').click(function(){
$.ajax({
type: 'POST',
utl: $('form.ajax').attr('action'),
data: new FormData($('form.ajax')[0]),
processData: false,
contentType: false
}).then(
function(error) {
console.log('good'+error);
},
function() {
console.log('bad');
}
);
event.preventDefault();
})
});
And when I add http_response_code script working good but when I change value for 500 I see in console still informations for error 200... Have you any ideas?

Categories