由于错误500,Laravel ajax请求无法正常工作

时间:2016-08-11 11:42:15

标签: php ajax laravel laravel-5 laravel-routing

我正在尝试创建ajax请求来创建新类别,但是由于错误500我得到了跟随错误消息我完全按照教程,但我不明白缺少什么

  

[2016-08-11 11:46:38] local.ERROR:异常'ErrorException',在/home/ubuntu/workspace/app/Http/Controllers/CategoryController.php中显示消息'从空值创建默认对象' :22

enter image description here

控制器:CategoryController.php

   <?php

   namespace App\Http\Controllers;

   use Illuminate\Http\Request;
   use App\Category;
   use Illuminate\Support\Facades\Response;

    class CategoryController extends Controller 
    {
      public function getCategoryIndex() 
       {
        $categories = Category::orderBy('created_at', 'desc')->paginate(5);
        return view('admin.blog.categories', ['categories' => $categories]);
       }

      public function postCreateCategory(Request $request) 
      {
        $this->validate($request, ['name'=>'required|unique:categories']);

        $cateogry = new Category();
        $category->name = $request['name'];

        if($category->save()) 
        {
           return Response::json(['message' => 'Category created.'], 200);
        }

        return Response::json(['message' => 'Error during creation.'], 404);
      }
    }

Javascript:categories.js

var docReady = setInterval(function() {
if(document.readyState !== 'complete') {
    return;
}

clearInterval(docReady);

//...
document.getElementsByClassName('btn')[0].addEventListener('click', 

createNewCategory);
}, 100);

function createNewCategory(event) {
event.preventDefault();

var name = event.target.previousElementSibling.value;

if(name.length === 0) {
    alert('Please enter a valid category name');

    return;
}

ajax("POST", "/admin/blog/category/create", "name=" + name, newCategoryCreated, [name]);
}

    function newCategoryCreated(params, success, responseObj) {
    location.reload();    
}

function ajax(method, url, params, callback, callbackParams) {
var http;

if(window.XMLHttpRequest) {
    http = new XMLHttpRequest;
}
else {
    http = new ActiveXObject('Microsoft.XMLHttp');
}

http.onreadystatechange = function() {
    if(http.readyState == XMLHttpRequest.DONE) {
        if(http.status == 200) {
            var obj = JSON.parse(http.responseText);

            callback(callbackParams, true, obj);
        }
        else if(http.status == 400) {
            alert('Category could not be saved. Please try again.');

            callback(callbackParams, false);
        }
        else  {
            var obj = JSON.parse(http.responseText);

            if(obj.message) {
                alert(obj.message);
            }
            else {
                alert('Please check the name');
            }
        }
    }   
}

http.open(method, baseUrl + url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(token);
http.send(params + '&_token=' + token);
}

路线

Route::group(['prefix'=>'/admin'],function() 
{
    Route::post('/blog/category/create',[
        'uses'  => 'CategoryController@postCreateCategory',
        'as'    => 'admin.blog.category.create'
    ]);
});

查看:categories.blade.php

    @extends('layouts.admin-master')

@section('styles')
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" type="text/css" />
    <link rel="stylesheet" href="{{ URL::secure('/src/css/categories.css') }}" type="text/css" />
@endsection

@section('content')
<div class="container">
    <section id="category-admin">
        <form action="" method="post">
            <div class="input-group">
                <label for="name">Category Name</label>
                <input type="text" name="name" id="name" />
                <button type="submit" class="btn">Create Category</button>
            </div>
        </form>
    </section>

    <section class="list">
        @foreach($categories as $category)
            <article>
                <div class="category-info" data-id="{{ $category->id }}">
                    <h3>{{ $category->name }}</h3>
                </div>

                <div class="edit">
                    <nav>
                        <ul>
                            <li class="category-list">
                                <input type="text" />
                            </li>

                            <li>
                                <a href="#">Edit</a>
                            </li>

                            <li>
                                <a href="#">Delete</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </article>
        @endforeach
    </section>

    @if($categories->lastPage() > 1)
        <section class="pagination">
            @if($categories->currentPage() !== 1)
                <a href="{{ $categories->previousPageUrl() }}"><i class="fa fa-caret-left"></i></a>
            @endif

            @if($categories->currentPage() !== $categories->lastPage())
            <a href="{{ $categories->nextPageUrl() }}"><i class="fa fa-

caret-right"></i></a>
                @endif
            </section>
        @endif
    </div>
@endsection

    @section('scripts')
    <script type="text/javascript">
        var token = "{{ Session::token() }}";
    </script>
    <script type="text/javascript" src="{{ URL::secure('src/js/categories.js') }}"></script>
@endsection

0 个答案:

没有答案