Ошибка 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

Я из базы достаю записи определенного пользователя. При желании пользователь может оставить комментарий к записи. Есть кнопка «Добавить комментарий», при нажатии на которую вываливается 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')

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

I am receiving an internal server error, status 500 and I don’t know how to troubleshoot. I have added error catch for the ajax call but doesn’t tell me much. How do I add code to understand what is going on inside the requesting file? I have tried doing a var_dump() but nothing happends.

    $('#createpanelbutton').live('click', function(){

        var panelname = $('#panelname').val();
        var user_cat = $('#user_cat').val();
        //var whocan = $('#whocan').val();
        var errors='';
        if(panelname=='')
            errors+='Please enter a Brag Book name.<br/>';
        if(user_cat=='0')
            errors+='Please select a category.<br/>';
        if(errors!=''){
            $('#panel_errors2').html('<span class="panel_brag_errors">'+errors+'</span>');
            return false;
        }else{

         $('#createpanelbutton').val('Creating Brag Book...');
            $.ajax({
                async:false,
                dataType:'json',
                type: 'POST',
                url:baseurl+'createpanel.php',
                error:function(data,status,jqXHR){ alert("handshake didn't go through")},
                data:'name='+encodeURIComponent(panelname)+'&category='+encodeURIComponent(user_cat)+'&collaborator='+encodeURIComponent('me'),
                success:function(response){
                    if(response.status=='success')
                        location.href=response.url;
                    if(response.status=='failure')
                        $('#panel_errors2').html('<span class="panel_brag_errors">'+response.message+'</span>');
                }
            });
        }
    });

Ajax call to to php file createpanel.php:

 <?php

include_once('s_header2.php');

if($_POST){

    if($_POST['name'] == ''){
            $msg = "Please enter Brag Book name.";
            $result = array("status"=>'failure', "message"=>$msg);
    }elseif($_POST['category'] == ''){
            $msg = "Please select category.";
            $result = array("status"=>'failure', "message"=>$msg);
    }else{

        $db = Core::getInstance();
        $dbUp = $db->dbh->prepare("SELECT id FROM ".USERS_PANEL." WHERE user_id = :uID and title = :tit");         
        $result = '2';
        $dbUp->execute(array(':uID'=>$_SESSION['sesuid'],':tit'=>$_POST['name']));
        $result = '3';
        $numrows = $dbUp->rowCount();
        $result = '4';
        if($numrows == 0){
         $result = '5';
        $dbIn = $db->dbh->prepare("INSERT INTO ".USERS_PANEL." (`user_id`,`title`,`category_id`,`desc`,`type`,`friend_id`) VALUES (?, ?, ?, ?, ?, ?)");

         $dbIn->execute(array($_SESSION['sesuid'],$_POST['name'],$_POST['category'],$_POST['panel_desc'],$_POST['collaborator'],$_POST['jj']));

         $lid = $db->dbh->lastInsertId();            
        //header("Location: ".BASE_URL.addslashes($_POST['bname'])."-".$lid."/");

        $panelurl=BASE_URL.$_POST['name']."-".$lid."/";
        $result = array("status"=>'success', "url"=>$panelurl, "name"=>$_POST['name'], "id"=>$lid);

        }else{              
            $result = array("status"=>'failure', "message"=>'You already have a Brag Book with that name.');
        }
    }

}

echo json_encode($result) ;die;

?>

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

Кроме того, я получаю такое же сообщение об ошибке, возможно, по другой причине. Мой 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>

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

  • Dec-23-2022
  • Techsolutionstuff

  • Laravel
    PHP
    jQuery

In this article, we will see 500 internal server errors in laravel 9 ajax. Also, we can see how to solve or fixed laravel 9 500 internal server error ajax. If you are fetching 500 internal server errors in jquery ajax post request in laravel 9. Here we will let you know how to fix the ajax post 500 (Internal Server Error) request in laravel 9.

Laravel provides the best security using the csrf token. So, you have each time pass csrf_token when you fire ajax in the post, delete or put a request. You can generate csrf token using the csrf_token() helper of laravel 9. we will see you how to generate csrf_token and pass on each ajax request of jquery. 

Also, you can add below meta tag and then you have to simply pass headers. It will automatically pass a 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 codes, you have to write on each page. So, you can simply put it on the layout page or common header page.


You might also like :

  • Read Also: Order By Query In Laravel 9 Example
  • Read Also: Socialite Login with Facebook Account In Laravel 9
  • Read Also: How To Solve The Page Expired 419 Error In Laravel
  • Read Also: User Roles And Permissions Without Package Laravel 9

RECOMMENDED POSTS

FEATURE POSTS

Понравилась статья? Поделить с друзьями:
  • Ошибка 500 при выполнении скрипта
  • Ошибка 500 почтовый сервер
  • Ошибка 500 почта майл ру
  • Ошибка 500 после переноса joomla
  • Ошибка 500 подключения к серверу