Passing data through Laravel Controller using ajax - php

I have two routes defined like this :
Route::get('directeur/qualite', 'Directeur\qualiteController#index')->name('qualite');
Route::get('directeur/qualite/{texte}','Directeur\qualiteController#getResultOfQuestion')->name('getResultQuestion');
My Controller have this function :
public function getResultOfQuestion(){
$texte=Input::get('texte');
$data = DB::table('questions')->where('texte','=',$texte)->value('code');
return['data'=>$data];
}
And I'm doing a request using Ajax like this :
$.ajax({
type: 'GET',
url: '/emagine/projet1613/public/directeur/qualite/',
data: {
texte: encodeURIComponent(str)
},
success: function (data) {
console.log(data);
},
error: function () {
alert('La requête n\'a pas abouti');
}
});
I would like to get the result of the function defined in the Controller but I can not do it. What am I doing wrong?

Just try this
Controller
public function getResultOfQuestion($texte){
$data = DB::table('questions')->where('texte','=',$texte)->value('code');
return response()->json(array('data' => $data));
}
AJAX request
$.ajax({
type: 'GET',
url: '/emagine/projet1613/public/directeur/qualite/'+encodeURIComponent(str),
success: function (data) {
console.log(data);
},
error: function () {
alert('La requête n\'a pas abouti');
}
});

You should return response:
return response()->json(compact('data'));

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.

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

How to use data serialized from ajax call

I have a problem.
I have an ajax call that have two data to send, one is a form serialized the other is a other variable, i don't know how to use the variables into the first data of ajax call ( the form serialized ) into PHP, how can i do this?
JS:
$.ajax
({
url: "/update",
type: "post",
data:
{
form: $("#formTeamLeaderProduzione").serialize(),
type: "TeamLeaderProduzione"
},
success: function (data)
{
alert(JSON.stringify(data))
},
error: function (msg)
{
alert(JSON.stringify(msg));
}
});
PHP:
Route::post('/update', function (\Illuminate\Http\Request $request)
{
$value = \Illuminate\Support\Facades\Input::get('form');
return response()->json($request->form->inputModificaNomeTeamLeaderProduzione1,200);
});
This is my anwser
Route::post('/update', function (\Illuminate\Http\Request $request)
{
parse_str($request->input('form'), $form);
return response()->json($form['inputModificaNomeTeamLeaderProduzione1'],200);
});

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