alzambo
alzambo

Reputation: 147

laravel 5: get ajax response in view

I'm trying to output an ajax success callback into a view:

Controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class AjaxTestController extends Controller
{
    public function ajax()
    {
        $nomi  = array();

        $nomi[0]['name'] = "alex";
        $nomi[0]['surname'] = "zambonin";

        $nomi[1]['name'] = "ciccio";
        $nomi[1]['surname'] = "pasticcio";

        return view('testAjax')->with('nomi',$nomi);

    }
}

View:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">

        <title>Laravel</title>

        <link rel="stylesheet" href="{{ URL::asset('assets/stylesheets/frontend.css') }}">

    </head>
    <body>
        @foreach ($nomi as $nome)
            {{ $nome['name'] }}<br/>
        @endforeach
    </body>

    <script src="{{ URL::asset('assets/javascript/frontend.js') }}"></script>
    <script>
        $.ajax({
            url: 'testajax',
            dataType: 'json',
            type: 'GET',
            success: function(data) {
                alert(data);
            }
        })
    </script>

</html>

I can get json data correctly displayed in html page but I cannot get not it in javascript alert. Also, I have a 404 error on firefox console; see this image

How to get it to work? Thanks Alex

Upvotes: 0

Views: 2181

Answers (1)

Dan H
Dan H

Reputation: 3623

You are getting a 404 because the URL /testajax doesn't exist. You need to create a route for that first. Then the response from your controller needs to be a JSON response, like so:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class AjaxTestController extends Controller
{
    public function myFancyWebsite()
    {
        return view('testAjax');
    }

    public function ajaxResponse()
    {
        $nomi  = array();

        $nomi[0]['name'] = "alex";
        $nomi[0]['surname'] = "zambonin";

        $nomi[1]['name'] = "ciccio";
        $nomi[1]['surname'] = "pasticcio";

        return response()->json($nomi);
    }
}

Now your ajax request should point to that method which simply returns a JSON response. But you need to create a route first in routes.php:

Route::get('somepage', 'AjaxTestController@myFancyWebsite');
Route::get('testajax', 'AjaxTestController@ajaxResponse');

Upvotes: 4

Related Questions