Меню

Ошибка 500 при запросе ajax

Can you post the signature of your method that is supposed to accept this post?

Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:

<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
    $.ajax({
        type:'POST',
        url:url,
        data:message,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success:successFunc,
        error:errorFunc
        });

};

Then my errorFunc javascript is like this:

function(request, textStatus, errorThrown) {
        $("#install").text("Error doing auto-installer search, proceed with ticket submissionn"
        +request.statusText); }

Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery’s library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:

<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

so check all that, and post your controller method signature in case that’s part of the issue

Can you post the signature of your method that is supposed to accept this post?

Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:

<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
    $.ajax({
        type:'POST',
        url:url,
        data:message,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success:successFunc,
        error:errorFunc
        });

};

Then my errorFunc javascript is like this:

function(request, textStatus, errorThrown) {
        $("#install").text("Error doing auto-installer search, proceed with ticket submissionn"
        +request.statusText); }

Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery’s library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:

<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

so check all that, and post your controller method signature in case that’s part of the issue

Can you post the signature of your method that is supposed to accept this post?

Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:

<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
    $.ajax({
        type:'POST',
        url:url,
        data:message,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success:successFunc,
        error:errorFunc
        });

};

Then my errorFunc javascript is like this:

function(request, textStatus, errorThrown) {
        $("#install").text("Error doing auto-installer search, proceed with ticket submissionn"
        +request.statusText); }

Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery’s library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:

<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

so check all that, and post your controller method signature in case that’s part of the issue

Я из базы достаю записи определенного пользователя. При желании пользователь может оставить комментарий к записи. Есть кнопка «Добавить комментарий», при нажатии на которую вываливается textarea с кнопкой «Добавить». Вот все это хочу сделать ajaxom. Текст из textarea я получаю, но все это дело в бд не попадает.

Вот скрипт:

$('.comment').click(function(){
		
	var id_advert = $(this).val();
	//console.log(id_advert);
	$(this).html("<textarea rows=10 cols=70 name='add_comment' class='add_comment' maxlengh='256' autofocus> </textarea><br><button type='submit' name='add' class='add'> Добавить сообщение</button>");
	$.get('edit_advert',{comment:id_advert},function()
		{
	$('.add').click(function(){	
	var params = $('.add_comment').serialize();
console.log(params);
	console.log($.post('add_comment',params));
	
		});
	
		});
});

Вот метод, который должен все это обрабатывать:

public function edit_advert(Request $request)
	{
		$id_advert = $_GET['comment'];
		$id_client = Auth::user()->id;
		$comment = $request->input('add_comment');
		
		Adverts::add_comment($comment,$id_client,$id_advert);
	

		
	}

Вьюшка:

<div class="panel-body">
				@foreach ($remember_adverts_client as $advert)

					<div class="table table-bordered">
                    Объявление добавлено <em> {{$advert->date}} </em> <br>
                    <strong>{{$advert->title}}</strong><br>
                    <strong>Тип недвижимости: </strong>{{$advert->type}}<br>
                    <strong>Количество комнат: </strong>{{$advert->quantity_room}}<br>
                    <strong>Город: </strong>{{$advert->city}}<br>
                   <strong> Описание: </strong> {{$advert->description}}<br>
                   <strong> Телефон: </strong>{{$advert->phone}}<br>
                   <!--<form action="edit_advert" method="GET"> -->
                   <button type="submit" value="{{$advert->id_realty}}" name="comment" class="comment"> Добавить комментарий</button>

                   <button type="submit" value="{{$advert->id_realty}}" name="cross"> Перечеркнуть </button>
                   <button type="submit" value="{{$advert->id_realty}}" name="lead">Обвести</button>
                   <button type="submit" value="{{$advert->id_realty}}" name="link">Поделиться ссылкой</button>
                   <!--</form> -->
				@endforeach

И роут:

Route::get('edit_advert','ClientController@edit_advert');
Route::post('add_comment','ClientController@edit_advert')

В чем может быть проблема?

Содержание

  1. Drupal Ajax error 500 – Let’s fix it
  2. Different causes for drupal ajax error 500 to occur
  3. 1. Insufficient memory
  4. 2. Bad permissions
  5. 3. Broken modules
  6. How we fix this drupal ajax error 500?
  7. Conclusion
  8. PREVENT YOUR SERVER FROM CRASHING!
  9. Laravel по-русски
  10. #1 06.04.2016 17:26:37
  11. Ошибка 500 при отправки AJAX
  12. Категории
  13. Подкатегории
  14. #2 06.04.2016 17:28:35
  15. Re: Ошибка 500 при отправки AJAX
  16. #3 06.04.2016 17:37:59
  17. Re: Ошибка 500 при отправки AJAX
  18. #4 06.04.2016 17:39:11
  19. Re: Ошибка 500 при отправки AJAX
  20. #5 06.04.2016 17:41:32
  21. Re: Ошибка 500 при отправки AJAX
  22. #6 06.04.2016 17:45:09
  23. Re: Ошибка 500 при отправки AJAX
  24. #7 06.04.2016 17:48:09
  25. Re: Ошибка 500 при отправки AJAX
  26. #8 06.04.2016 17:59:00
  27. Re: Ошибка 500 при отправки AJAX
  28. #9 06.04.2016 18:16:34
  29. Re: Ошибка 500 при отправки AJAX

Drupal Ajax error 500 – Let’s fix it

Isn’t it annoying to see the “drupal ajax error 500” error plaguing your website?

This is one of the common Drupal errors you will encounter while running a website.

This error occurs due to many reasons that include insufficient memory, bad permissions, and so on.

Here at Bobcares, we often receive requests to resolve drupal errors as a part of our Server Management Services for web hosts and online service providers.

Today, let’s discuss the different causes for this error to occur and see how our Support Engineers fix it.

Different causes for drupal ajax error 500 to occur

Let’s now look into the different reasons that cause this error.

1. Insufficient memory

If there isn’t sufficient memory to run the process it causes this error to occur.

So it is better to set a greater memory in the php.ini file. We can also set this memory limit in the .htaccess file as well.

2. Bad permissions

Bad permissions are one of the most common reasons that cause errors in the website.

Even, for drupal ajax error 500 to occur, improper permissions also can be one of the reasons.

3. Broken modules

Customers do enable modules on the website for better performance. In case, if these modules break then it will create a problem without the insight of the website owner.

So, it is best to uninstall the module and then get it re-installed and check if it was causing an error.

How we fix this drupal ajax error 500?

One of our customers was trying to install Drupal Open Enterprise and received an error message as shown below:

Let’s now see how our Support Engineers fix this error.

First, we started to troubleshoot the error by increasing the PHP parameters. We increase the memory_limit in the php.ini file.

Here are the parameters that we set in the php.ini file.

And then we added the below line in .htaccess file

Next, we verified the permission of sites/default/settings.php and sites/default folder.

Browsing to the folder where drupal was extracted we made a copy of sites/default/default.settings.php to sites/default/settings.php

And then ensured permissions were set correctly on both the paths by running the command.

After the changes, we were able to install drupal without any error.

[Need any assistance in fixing drupal error? – We’ll are always there to help you]

Conclusion

In short, the drupal ajax error 500 occurs due to various reasons like insufficient memory, bad permissions, and broken modules. Today, we discussed the different reasons that cause this error and saw how our Support Engineers fix it.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

Laravel по-русски

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

#1 06.04.2016 17:26:37

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

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

Категории

@if (count($categories) > 0)

@endif
@endforeach

Категория «<< $category->name >>» ‘adminzone/delete_category’)) !!>
id) !!>
<< Form::submit(‘Удалить’) >>
id >>»>Подкатегории

@foreach ($categories as $category) @if ($category->parent == 0)

@else
I don’t have any records!
@endif

Подкатегории

добавлен в 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);
>
>);
>);
>);
%%

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

Не в сети 24.03.2016

#2 06.04.2016 17:28:35

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

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

Не в сети 11.11.2014

#3 06.04.2016 17:37:59

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

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

Не в сети 24.03.2016

#4 06.04.2016 17:39:11

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

Не в сети 11.11.2014

#5 06.04.2016 17:41:32

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

[2016-04-06 13:43:15] local.ERROR: exception ‘IlluminateSessionTokenMismatchException’ in /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:67
Stack trace:
#0 [internal function]: IlluminateFoundationHttpMiddlewareVerifyCsrfToken->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#3 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#4 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#5 [internal function]: IlluminateViewMiddlewareShareErrorsFromSession->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#8 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#9 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(62): IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#10 [internal function]: IlluminateSessionMiddlewareStartSession->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#13 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#14 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#15 [internal function]: IlluminateCookieMiddlewareAddQueuedCookiesToResponse->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#18 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#19 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#20 [internal function]: IlluminateCookieMiddlewareEncryptCookies->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#23 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#24 [internal function]: IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#25 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#26 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(726): IlluminatePipelinePipeline->then(Object(Closure))
#27 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(699): IlluminateRoutingRouter->runRouteWithinStack(Object(IlluminateRoutingRoute), Object(IlluminateHttpRequest))
#28 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): IlluminateRoutingRouter->dispatchToRoute(Object(IlluminateHttpRequest))
#29 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): IlluminateRoutingRouter->dispatch(Object(IlluminateHttpRequest))
#30 [internal function]: IlluminateFoundationHttpKernel->IlluminateFoundationHttp(Object(IlluminateHttpRequest))
#31 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#32 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#33 [internal function]: IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#36 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#37 [internal function]: IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#38 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#39 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): IlluminatePipelinePipeline->then(Object(Closure))
#40 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): IlluminateFoundationHttpKernel->sendRequestThroughRouter(Object(IlluminateHttpRequest))
#41 /var/www/uni08.loc/public/index.php(54): IlluminateFoundationHttpKernel->handle(Object(IlluminateHttpRequest))
#42


[2016-04-06 14:09:34] local.ERROR: exception ‘SymfonyComponentDebugExceptionFatalErrorException’ with message ‘Class ‘AppHttpControllersResponse’ not found’ in /var/www/uni08.loc/app/Http/Controllers/AdminController.php:43
Stack trace:
#0

[2016-04-06 14:33:29] local.ERROR: exception ‘SymfonyComponentDebugExceptionFatalErrorException’ with message ‘Class ‘AppHttpControllersResponse’ not found’ in /var/www/uni08.loc/app/Http/Controllers/AdminController.php:43
Stack trace:
#0

Не в сети 24.03.2016

#6 06.04.2016 17:45:09

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

Добавил в контроллер
use AppHttpControllersResponse;

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

Не в сети 24.03.2016

#7 06.04.2016 17:48:09

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

[2016-04-06 14:43:56] local.ERROR: exception ‘SymfonyComponentDebugExceptionFatalErrorException’ with message ‘Class ‘AppHttpControllersResponse’ not found’ in /var/www/uni08.loc/app/Http/Controllers/AdminController.php:44
Stack trace:
#0

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

Не в сети 24.03.2016

#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 AppHttpControllersResponse 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]: IlluminateRoutingRoute->IlluminateRouting(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): IlluminateRoutingRoute->signatureParameters(‘IlluminateData. ‘)
#4 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(844): IlluminateRoutingRouter->substituteImplicitBindings(Object(IlluminateRoutingRoute))
#5 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(827): IlluminateRoutingRouter->substituteBindings(Object(IlluminateRoutingRoute))
#6 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(691): IlluminateRoutingRouter->findRoute(Object(IlluminateHttpRequest))
#7 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): IlluminateRoutingRouter->dispatchToRoute(Object(IlluminateHttpRequest))
#8 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): IlluminateRoutingRouter->dispatch(Object(IlluminateHttpRequest))
#9 [internal function]: IlluminateFoundationHttpKernel->IlluminateFoundationHttp(Object(IlluminateHttpRequest))
#10 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#11 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#12 [internal function]: IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode->handle(Object(IlluminateHttpRequest), 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]: IlluminatePipelinePipeline->IlluminatePipeline(Object(IlluminateHttpRequest))
#15 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#16 [internal function]: IlluminateRoutingPipeline->IlluminateRouting(Object(IlluminateHttpRequest))
#17 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(IlluminateHttpRequest))
#18 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): IlluminatePipelinePipeline->then(Object(Closure))
#19 /var/www/uni08.loc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): IlluminateFoundationHttpKernel->sendRequestThroughRouter(Object(IlluminateHttpRequest))
#20 /var/www/uni08.loc/public/index.php(54): IlluminateFoundationHttpKernel->handle(Object(IlluminateHttpRequest))
#21

видимо надо выпить пива и покурить 🙂

Не в сети 24.03.2016

#9 06.04.2016 18:16:34

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

Добавил в контроллер
use AppHttpControllersResponse;

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

видимо надо выпить пива и покурить 🙂

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

local.ERROR: exception ‘IlluminateSessionTokenMismatchException’

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

Источник

Помогите, пожалуйста… вторые сутки бьюсь да без толку
Задача состоит в том, чтобы вывести Подкатегории по клику на кнопку Родительской категории…
Вроде просто, мной делалось такое на раз-два при написании компонентов для 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… }

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

Nov 11, 2021 . Admin

Hi Dev,

If you are fetching 500 internal server error in jquery ajax post request in laravel 8, then you are a right place. Here i will let you know how to fix 500 (internal server error) ajax post request in laravel 8.

If you know well laravel then you know about csrf token, laravel provide best security using csrf token. So you have each time pass csrf_token when you fire ajax post, delete or put request. You can generate csrf token using csrf_token() helper of laravel 8.

So, Here i will see you how to generate csrf_token and pass on each ajax request of jquery. So let’s you have to add bellow meta tag and then you have to simple pass headers. It will automatically pass token on each post request.

Add Meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

Add JS Code:

$.ajaxSetup({
    headers: {
    	'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

As above both code, you have to write in each page so you can simply put in layout page.

I hope it help you…

#Laravel 8
#Laravel

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

You might also like…

  • Laravel 8 Autocomplete Search using Typeahead JS Example Tutorial
  • Laravel 8 Ajax Image Upload Example
  • Laravel 8 Ajax Form Validation Example
  • Laravel 8 Ajax Autocomplete Search from Database Example
  • Laravel 8 Redirect User to Previous Page After Login
  • How To Handle «No Query Results For Model» Error — Laravel 8

И где же ты тут мою «ошибочку»  увидел?!!!

1е — Это не ошибка, а новое имя параметра. Читай доки http://api.jquery.com/jquery.ajax/

2е — по дефолту в симпле версия 1.7.2. С этой точки зрения type — да правильно.

Но ТС использовал параметр method (поэтому я его и оставил). 

AFI

1 строка должна быть:

$html = $_POST['html'];

И в дальнейшем если «не работает» — то пишите что именно.

Какая ошибка или что происходит.

Мы не экстрасенсы…

А вообще, для начала, не плохо было бы описать суть затеи

То я что то совсем не соображу что это!

Отправляется аякс запрос на сервер где переданная в post

 засовывается в pdf и (насколько я знаю библиотеку mpdf) - полученный pdf (Output с флагом I) - отдается назад аяксу.

У которого (судя по вашим постам) даже нет функции для обработки.

И в чем тут логика и что должно работать?

Конечно, описанные Вами недостатки имеют место, но ТС пока в первом посте ставил вопрос более простой: пофиксить ошибку 404. А для ошибки в ajax/mpdf.php возможностей много, например:

1. Первая же строка даст для $html пустое значение.

2. Во второй строке, очень возможно, неверный путь, и не срабатывает подключение.

3. По ходу могут возникнуть PHP-сообщения об ошибках…

А чтоб узнать точно, надо, как Вы правильно заметили, иметь полную информацию…

Увы, часто спрашивают  весьма легкомысленно — ляпнул что-то кое-как, не озаботившись сообщить детали.

Например, если бы в этой теме ТС сразу дал URL, можно было бы многое определить точнее…

Суть описал, но не подробно.  Мой косяк. Задумка была в том, что человек кликает на кнопку, js забирает часть html и отправляет его в php где создается пдф и автоматом скачивается(в Output параметр D изменил).

А по поводу ошибок, все что я имел на тот момент я написал. Когда получил доступ к логам

ошибки стали явны, не работал autoloader, ругался на __DIR__ или когда подключал на прямую пропустил /.

А вот по поводу функции обработки можно поподробней? Как js обработает файл которЫй вернет output?

Можете ли вы опубликовать подпись своего метода, который должен принять этот пост?

Кроме того, я получаю такое же сообщение об ошибке, возможно, по другой причине. Мой YSOD рассказывал о словаре, не содержащем значения для значения, не имеющего значения NULL.
То, как я получил информацию YSOD, заключалось в том, чтобы поставить точку останова в функцию $.ajax, которая обрабатывала ошибку, как показано ниже:

<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
    $.ajax({
        type:'POST',
        url:url,
        data:message,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success:successFunc,
        error:errorFunc
        });

};

Тогда мой javascript errorFunc выглядит так:

function(request, textStatus, errorThrown) {
        $("#install").text("Error doing auto-installer search, proceed with ticket submissionn"
        +request.statusText); }

Используя IE, я отправился в меню просмотра → script отладчик → перерыв в следующей инструкции.
Затем отправился запускать код, который запустил бы мой пост. Обычно это меня куда-то глубоко внутри библиотеки jQuery, а не там, где я хотел, потому что в раскрывающемся меню select вызывается jQuery. Таким образом, я нажимаю StepOver, тогда и следующая следующая строка также сломается, и именно там я и хотел быть. Затем VS переходит в режим клиентской стороны (динамический) для этой страницы, и я вложил разрыв в строку $("#install"), чтобы я мог видеть (используя мышь над отладкой) то, что было в запросе, textStatus, errorThrown. запрос. В request.ResponseText появилось сообщение html, где я увидел:

<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

так что проверьте все это и опубликуйте подпись своего контроллера в случае, если часть проблемы

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка 500 при загрузке страницы
  • Ошибка 5005 0x80070002 при удалении программы