I am trying to figure out the best way to fetch data from my Laravel controller and show it using JavaScript on a webpage. How should I approach this?
Here is the code snippet of my controller and ajax call:
var jq = jQuery.noConflict();
var id = jq("#category_id").val();
jq.ajaxSetup({
headers: {'X-CSRF-Token': jq("meta[name='_token']").attr('content')}
});
jq.ajax({
url: '/netaviva/sportquiz/public/quiz/'+id+'/questions',
type: 'GET',
dataType: 'json',
success: function(data){
if(data['success']){
jq(data.records).each(function(i, item){
console.log(item);
});
}
}
});
public function index($category_id)
{
$questions = Question::where('category_id', '=', $category_id)->orderBy(DB::raw('RAND()'))->take(3)->get()->toJson();
return View::make('pages.questions',compact('questions', 'category_id'));
}
Route handling the controller request
Route::match(['GET', 'POST'], '/{id}/questions', [
'uses'=>'QuestionController@index',
'as'=>'question'
]);