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

When ever I am doing an ajax request with jquery I always get an error 500 return,

I am posting to the following URL

http://localhost/domain/index.php/my_profile/interests_music

using this javascript,

$("#add").click(function(e){

    //set some process variables, we need to get the forms action, 
    //and any post data it is sending appending isAjax into the params
    //gives us a point in the controller to gracefully check for ajax.
    var action = $(this).parent('form').attr('action');
    var formData = $(this).parent('form').serialize()+"&isAjax=1";

    $.ajax({
        type: "POST",
        url: action,
        data: formData
    }).done(function( msg ) {
        alert( "Data Saved: " + msg );
    });

    e.preventDefault();
});

The params that are being sent are,

music=Savage Garden&isAjax=1

And the PHP method the ajax is requesting looks like this,

public function interests_music()
{
    if($this->input->post('music'))
    {
        $this->rest->initialize(array('server' => 'https://www.googleapis.com/freebase/v1'));
        $response = $this->rest->get('mqlread?query={"type":"/music/artist","name":"' . urlencode($this->input->post('music')) . '","id":[]}');
        $data['image'] = 'https://usercontent.googleapis.com/freebase/v1/image'.$response->result->id[0].'?mode=fillcrop&maxwidth=80&maxheight=80';
        $data['category'] = 'music';
        $data['user_id'] = $this->session->userdata('id');
        $data['name'] = $this->input->post('music', TRUE);

        $this->profile_model->add_interest($data);

        Events::trigger('interests_music');
        Events::trigger('badge_stagediver');

        if($this->input->post('isAjax') == 1)
        {
            echo json_endcode($data);
            $this->_buttons();
        }

        redirect('my_profile/interests');
    }
    else
    {
        show_404();
    }
}

Am I missing something, is this a common problem?

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

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

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

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

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

Question

Having a problem with WordPress Ajax calls. In the development environment and in the admin mode on the production server, the ajax works perfectly. When the JQuery post call is made by the same code and with the same, well formatted, request data on the front-end, it fails. Debugged the client side and got the same server response with both the Safari Web Inspector and the Chrome Developer tools. The error message is Internal Server Error (500). What’s going on with IIS 10.0 ? How to set up IIS to accept front-end Ajax calls? Should I install Ajax.Net ?

Solution

AJAX (Asynchronous JavaScript And XML) is a client-side technology. On the server side the IIS can’t distinguish between normal web page and AJAX POST, GET requests. There is no need to ‘setup’ your IIS or Apache for AJAX. jQuery is nothing else than an easy-to-use wrapper for the native JavaScript. ASP.NET AJAX is a set of technologies to add AJAX support to ASP.NET. It integrates client script libraries with the ASP.NET. It has nothing to do with your PHP WordPress side.

500 internal server error is an irritating all-you-cannot-eat message. To trace the error, first look at the logs of IIS to discover something more about the infamous error, and second, find and look at the WordPress plugins and themes, ie. the PHP code. The typical cause is conflicts between plugins and/or themes, including child theme with your code. It’s true for other technologies as well, always look at the web site installation, identify possible conficts, and check out your server side code.

IIS detailed error log

1. On Windows Server 2008/2012 you can use Advanced Logging option of IIS 7.5 or 8. You may need to download and install it from Microsoft. Check out the latest version if it’s already available for IIS 10.

2. Go to the server. Just to be sure, look at the folders of PHP and website if permissions are set properly. Open IIS Manager, select server and website. Enable Trace Logging for Failed Requests regardless of the use of the Advanced Logging option. In the Actions pane at the Configure group, click Failed Request Tracing and set the directory you will use:

IIS trace error

3. Open your web browser and load the website. When needed, activate whatever you need to run the AJAX call, for example click on a button if that initiate the call. Recheck AJAX ‘data’ request if it’s really formatted well.

4. Go back to the server, find the log directory where you will be greated by a couple of large xml files. Open the latest one the IIS generated when serving your site’s request. If you run into an access error, copy the file into a folder where you have open/read permissions. Well, you’ll spend some time to locate the line you really wanted to see. Like this:

IIS trace error

Now we know that in this case the 500 error is triggered by ‘Reached the end of the file’. That rarely means the PHP had problems reading a physical file though.

WP plugin conflicts at handling AJAX calls

1. Must do checklist

– Step A: disable all other plugins or themes.

– Step B: reload the web site on the client side. Check out if the 500 error pops up. If not, activate the next plugin.

– Step C: go back to Step B and repeat it until the suspect has been caught. If you are lucky.

If not, your code is likely in conflict with WordPress (PHP installation) or parent theme.

2. PHP, WordPress and your code

Probably you are unlucky and found nothing so far. Switch on WP debug mode (wp-config.php) and see if it helps locate suspects:

Likely found something relevant here.

3. admin-ajax.php

You may want to diagnose and look at admin-ajax.php to see how server responses (How ? Use Chrome Developer tools for example). Initially admin-ajax.php was used for autosave, post locking and log-in expiration warnings. You will notice third party plugins polling this file frequently, thinking it’s a horse race, that may cause problems without any code error, but doing nothing good at all. Each POST request had a corresponding PHP script execution on the server using expensive CPU time.

4. Your code

We all have bad days and write bad codes, and sometimes need another two eyes to catch the obvious. Invite someone to look at your code and offer a free cup of tea.

Like this post? Please share to your friends:
  • Jquery validate вывод ошибок
  • Jquery getjson ошибка
  • Jquery ajax получить код ошибки
  • Jquery ajax вывести ошибку
  • Jquery ajax post обработка ошибок