Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

Ты не вошёл. Вход тут.

#1 06.04.2016 17:26:37

Ошибка 500 при отправки AJAX

Помогите, пожалуйста... вторые сутки бьюсь да без толку
Задача состоит в том, чтобы вывести Подкатегории по клику на кнопку Родительской категории...
Вроде просто, мной делалось такое на раз-два при написании компонентов для Joomla 2-3...
А вот взялся знакомиться с Ларой 5... и такой финт ушами. 

Представление
%%(php)
<div class="col_50">
    <h2>Категории</h2>
@if (count($categories) > 0)
    <table border="0">
    @foreach ($categories as $category)   
    @if ($category->parent == 0)
        <tr><td>Категория "{{ $category->name }}"</td>
        <td>
            {!! Form::open(array('url' => 'adminzone/delete_category')) !!}
            {!! Form::hidden('categoty_id', $category->id) !!}
            {{ Form::submit('Удалить') }}
            {!! Form::close() !!}
        </td>
        <td><button class="category" id="{{ $category->id }}">Подкатегории</button></td></tr>
    @endif   
@endforeach
    </table>
@else
    I don't have any records!
@endif
</div>
<div class="col_50" id="subcategories">
<h2>Подкатегории</h2>
    <div id="result">
    </div>   
</div>
%%

<meta name="_token" content="{!! csrf_token() !!}"> добавлен в master.blade.php

Скрипт
%%(js)
$(document).ready(function(){
    $('.category').click(function(e){
        var my_category = $(this).attr("id");
        var token  = $('meta[name=_token]').attr('content');
        e.preventDefault();
        //$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': token }});     
        var mydata = {};
        mydata['_token'] = token;           
        mydata['id'] = my_category;           
               
        $.ajax({
            method: "POST",
            url: "../subcategories",
            cache: false,
            data: mydata,
            dataType: 'json',
            beforeSend: function(xhr){
                //alert(mydata['_token']);
                xhr.setRequestHeader('X-CSRF-TOKEN', token);
                },   
            success: function (htmt) {
                console.log('Success');
                //$('#result').html(msg);
                //alert( "Прибыли данные: " + msg );
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });   
});
%%

Error
POST
XHR
http://uni08.loc/subcategories [HTTP/1.0 500 Internal Server Error 104мс]
Error: Object { readyState: 4, getResponseHeader: .ajax/w.getResponseHeader(), getAllResponseHeaders: .ajax/w.getAllResponseHeaders(), setRequestHeader: .ajax/w.setRequestHeader(), overrideMimeType: .ajax/w.overrideMimeType(), statusCode: .ajax/w.statusCode(), abort: .ajax/w.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), ещё 11… }

Спасибо за внимание. Умные люди, помогите.

Не в сети

#2 06.04.2016 17:28:35

Re: Ошибка 500 при отправки AJAX

суть ошибки в  чем? в лог посмотри

Не в сети

#3 06.04.2016 17:37:59

Re: Ошибка 500 при отправки AJAX

Для этого надо логирование включить? Или где-то по-дефолту есть?!

Не в сети

#4 06.04.2016 17:39:11

Re: Ошибка 500 при отправки AJAX

storage/logs/laravel.log

Не в сети

#5 06.04.2016 17:41:32

Re: Ошибка 500 при отправки AJAX

[2016-04-06 13:43:15] local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:67
Stack trace:
#0 [internal function]: Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#1 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#2 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#3 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#4 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#5 [internal function]: Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#6 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#7 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#8 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#9 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(62): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#10 [internal function]: Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#11 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#12 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#13 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#14 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#15 [internal function]: Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#17 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#18 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#19 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#20 [internal function]: Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#21 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#22 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#23 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#24 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#25 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#26 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(726): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#27 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(699): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#28 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#29 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#30 [internal function]: Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#31 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#32 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#33 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#34 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#35 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#36 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#37 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#38 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#39 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#40 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#41 /var/www/uni08.loc/public/index.php(54): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#42 {main} 
[2016-04-06 14:09:34] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\Response' not found' in /var/www/uni08.loc/app/Http/Controllers/AdminController.php:43
Stack trace:
#0 {main} 
[2016-04-06 14:33:29] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\Response' not found' in /var/www/uni08.loc/app/Http/Controllers/AdminController.php:43
Stack trace:
#0 {main}

Не в сети

#6 06.04.2016 17:45:09

Re: Ошибка 500 при отправки AJAX

Добавил в контроллер
use App\Http\Controllers\Response;

ошибка 500 осталась....

Не в сети

#7 06.04.2016 17:48:09

Re: Ошибка 500 при отправки AJAX

[2016-04-06 14:43:56] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\Response' not found' in /var/www/uni08.loc/app/Http/Controllers/AdminController.php:44
Stack trace:
#0 {main} 

видимо из-за
public function get_subcategories(Request $request){
        $categoty_id = $request->input('id');
        return Response::json(array('msg' => 'усё окей шеффф '.$categoty_id));
    }

Не в сети

#8 06.04.2016 17:59:00

Re: Ошибка 500 при отправки AJAX

public function get_subcategories(Request $request, Response $response){
        $categoty_id = $request->input('id');
        return $response->json(['msg' => 'усё окей шеффф '.$categoty_id]);
    }

[2016-04-06 14:56:46] local.ERROR: exception 'ReflectionException' with message 'Class App\Http\Controllers\Response does not exist' in /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Route.php:270
Stack trace:
#0 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Route.php(270): ReflectionParameter->getClass()
#1 [internal function]: Illuminate\Routing\Route->Illuminate\Routing\{closure}(Object(ReflectionParameter))
#2 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Route.php(271): array_filter(Array, Object(Closure))
#3 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(859): Illuminate\Routing\Route->signatureParameters('Illuminate\Data...')
#4 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(844): Illuminate\Routing\Router->substituteImplicitBindings(Object(Illuminate\Routing\Route))
#5 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(827): Illuminate\Routing\Router->substituteBindings(Object(Illuminate\Routing\Route))
#6 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(691): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#7 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#8 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#9 [internal function]: Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#10 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#11 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#12 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#13 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)
#14 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#15 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#16 [internal function]: Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#17 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#18 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#19 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#20 /var/www/uni08.loc/public/index.php(54): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#21 {main} 

видимо надо выпить пива и покурить :-)

Не в сети

#9 06.04.2016 18:16:34

Re: Ошибка 500 при отправки AJAX

Добавил в контроллер
use App\Http\Controllers\Response;

Стесняюсь спросить - зачем?

видимо надо выпить пива и покурить :-)

Лучше книжку почитать  о php для начала ) потом уже мануал лары


local.ERROR: exception 'Illuminate\Session\TokenMismatchException'

https://laravel.com/docs/master/routing … csrf-token

Либо отключить его нахер (в app/Http/Kernel закомментить строку \App\Http\Middleware\VerifyCsrfToken::class, )
с ним больше проблем на самом деле, никому ваши  мелкосайты не нужны, никто подделывать сабмиты форм не будет

Не в сети

#10 06.04.2016 20:43:29

Re: Ошибка 500 при отправки AJAX

Спасибо, О Великий Гуру на науку! -)))
Буду курить мануалы....

Не в сети

#11 06.04.2016 21:31:17

Re: Ошибка 500 при отправки AJAX

Ура, товарищи! Ура! Еще раз спасибо VitalN за хороший пендель в нужном направлении! Заработало!...

Скрипт

$(document).ready(function(){
	$('.category').click(function(e){
		var my_category = $(this).attr("id");
		var token  = $('meta[name=_token]').attr('content');
		e.preventDefault();
		$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': token }});     
		var mydata = {};
		mydata['_token'] = token;           
		mydata['id'] = my_category;           
				
		$.ajax({
			method: "POST",
			url: "../subcategories",
			cache: false,
			data: mydata,
			dataType: 'json', 
			success: function (response) {
				$('#result').html(response['msg']);
			},
			error: function (data) {
                console.log('Error:', data);
            }
		});
    });	
});

В представлении не забываем

<meta name="_token" content="{!! csrf_token() !!}">
...
<button class="category" id="{{ $category->id }}">Подкатегории</button>
....

Контроллер

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\Controller;
use Collective\Html\FormFacade;
use DB;
use Response; //Обязательно!

class AdminController extends Controller
{
   .....
	public function get_subcategories(Request $request){
		$categoty_id = $request->input('id');
		return Response::json(['msg'=>$categoty_id]);
	}	
	....
}

Всем спасибо, всем пока!

Не в сети

Подвал раздела