Erylis
Erylis

Reputation: 101

Passing data through Laravel Controller using ajax

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?

Upvotes: 2

Views: 777

Answers (2)

Jaymin Panchal
Jaymin Panchal

Reputation: 2856

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

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You should return response:

return response()->json(compact('data'));

Upvotes: 0

Related Questions