Post запрос ошибка 500

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')

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

Posted 5 years ago by Ryan Dhungel

Category: JavaScript React Laravel

Viewed 20324 times

Estimated read time: 2 minutes

Have you been getting 500 Internal Server Error in your Laravel project every time you make a POST request from JavaScript side of your application using Vue JS or React JS?

There might be three possible reasons

  • You are not using the correct post route
  • You have not set the protected fillable fields in your model
  • You are not sending all required fields for example title and body

Possible solutions

Make sure you are using post route such as Route::post(‘/blogs’);

Set the fillable fields, for example here on my Blog model, I have set these fields fillable:

protected $fillable = ['title', 'body'];

Send all the required fields in your post request. Here I have send the title and body as POST request from react component using axios

        axios
            .post('/blog/store', {
                title: this.state.title,
                body: this.state.body
            })
            .then(response => {
                console.log('from handle submit', response);
            });

you can also try setting mysql strict mode to false in config/database.php and see what happens:

'strict' => false,

It changing strict to false fixes the issue, then you are not sending all the fields on your post request.

Easy debugging:

When you make such GET or POST request from JavaScript side of your application, always open the network tab in the google chrome console and click on the post link that appears. Click on that link and click on Preview tab to see the error messages etc.

Hope you were able to pass through your error messages. If so.. congrats!



automated-testing.info

Загрузка…

  • testomat.io управление авто тестами
  • Python
  • Реклама
  • Работа
  • Консультации
  • Обучение
Fixed - Ajax Post 500 (Internal Server Error) In Laravel 8

Hi Guys,

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 fixed Ajax Post 500 (Internal Server Error) 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 7

#Laravel

#Laravel 6

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

Понравилась статья? Поделить с друзьями:
  • Polyvision cms ошибка соединения
  • Polyvision cms неустранимая ошибка приложения
  • Polykraft alpine light 24 f коды ошибок
  • Polina look at the seals исправь пунктуационные ошибки
  • Poligon dll ошибка 429