How to send json from laravel correctly, and then take it to js? As I understand it, this code sends json to the index page, but how can js accept this json?

$even = DB::table('Table')->select('Name', 'Location')->get(); $jeven = json_encode($even); $data = ['Title'=>'заголовок', 'even'=>$jeven]; return view('index', $data); 

    3 answers 3

    In the controller, return

     return Response::json($data); 

    In js, process the response if the request is successful or fails.

      success: function(data){ out = JSON.parse(data); title = out.title; // обрабатываем успешное выполнение запроса }, error: function() { // выводим инфу об ошибке } 
    • And if I need to return everything in the controller as $ data = ['Title' => 'title', 'even' => $ jeven]; return view ('index', $ data); - Xenvert
    • one
      @Xenvert Why do you want to give a twist to the ajax request? Check in the controller, if ajax request is an if (Request::ajax()) , then give the json object, if not, then give the view - LANSELOT
    • It's just that this ajaxa function is stuck in onload () :) it turns out I need to return both the view and json - Xenvert

    If you have laravel 5, the best solution to return json will be to send a new JsonResponse object. return new Illuminate\Http\JsonResponse($data);

      How you are doing is a working version. In View, the variables $Title and $even will be available.

      It remains to display the json-string and assign the JS-variable:

       var data; try { data = <?php echo $even; ?>; } catch(e) { // в случае ошибки можно назначить default data = []; };