Get 500 internal server error ajax

I am trying to perform this AJAX post but for some reason I am getting a server 500 error. I can see it hit break points in the controller. So the problem seems to be on the callback. Anyone? $.aj...

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

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

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

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

  • Remove From My Forums
  • Question

  • User-1575600908 posted

    i have a problem for pass data in $.ajax,

    i want pass data in $.ajax but when run project i get null data in c# code , i created breack point in code behind and get this error: Object reference not set to an instance of an object and in firebug i get this error: 500 Internal Server
    Error

     my url params in $.ajax was passed but
    data
    don’t pass :( where wrong my code? please help me

    var value= {
        oldpassword: $('#oldpassword').val(),
        newpassword: $('#newpassword').val()
    }
    
    $.ajaxService({
        url: 'http://localhost:1549/Store/Pages/services.aspx?ServiceName=hello-world',
        data:JSON.stringify(value),
        onStartService: function () {
            $(options.target).addClass('loading');
        },
        onEndService: function () {
            $(options.target).removeClass('loading');
        },
        onResponse: function (response) {
            if (response.result == '1') {
                $.pushMessage({
                    message: 'success',
                    messageClass: 'success-message',
                    delay: 3000
                });
            else {
                $.pushMessage({
                    message: 'error',
                    messageClass: 'success-message',
                    delay: 3000
                });
            }
        }
    });
    }
    NameValueCollection ResponseResultCollection = new NameValueCollection();
    
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(2200);
        string serviceName = this.Request.QueryString["ServiceName"];
        if (!string.IsNullOrEmpty(serviceName))
        {
            switch (serviceName.ToLower().Trim())
            {
                case ("hello-world"):
                    string oldpassword = Request["oldpassword"].ToString();// its null
                    string newpassword = Request["newpassword"].ToString();//its null
                    try
                    {
                        System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
                        if (usr.ChangePassword(oldpassword, newpassword))
                            ResponseResultCollection["result"] = "1";
                        else
                            ResponseResultCollection["result"] = "0";
                    }
                    catch (Exception ex) { 
                        Response.Write("An exception occurred: " + Server.HtmlEncode(ex.Message) + ". Please re-enter your values and try again."); 
                    }
                    break;
                }
            }
            Response.Write(this.GenerateResponseResult());
            Response.End();
        }
    
        private string GenerateResponseResult()
        {
            string result = "";
    
            foreach (string key in this.ResponseResultCollection.AllKeys)
            {
                result += string.Format(","{0}":"{1}"", key, this.ResponseResultCollection[key]);
            }
    
            if (!string.IsNullOrEmpty(result))
            {
                result = result.Substring(1);
                result = "{" + result + "}";
            }
    
            return result.ToString();
        }

Answers

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

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

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

Quote:

Make sure that internally web server maintains some kind of internal error logs that gives more detail of what went wrong and thus help in diagnosing the issue. Generally, it is logged into Windows Event Logs on the server. Thus, first thing while troubleshooting the error is to see Windows Event Logs on the server to find what went wrong.

Other useful thing to troubleshoot it would be to disable friendly HTTP error messages to see if the raw content can provide a direction to look more. Steps:

Go to menu Tools/Internet Options in your IE.
Click on the Advanced tab & then uncheck “Show friendly HTTP error messages” option and then click OK.
Now, when on accessing the same web page, much more developer meaningful error message will be shown.

Moving on, following are most common:

Option #1: HRESULT: 0×80070035 – The page cannot be displayed because an internal server error has occurred. This occurs because the server that is running IIS cannot access the configured root directory of the requested location.

Resolution would be to make sure that the server that is running IIS can access the configured root directory of the requested location.

Option #2: HRESULT: 0x800700c1 – The page cannot be displayed because an internal server error has occurred. This occurs because a script mapping is not valid.

Resolution would be to make sure that the script mapping points to the ISAPI.dll file that can process the request. To do this, follow these steps:

Click Start, click Run, type inetmgr.exe, and then click OK.
In IIS Manager, expand server name, expand Web sites, and then click the Web site that you want to modify.
In Features view, double-click Handler Mappings.
Make sure that the script mapping points to the correct ISAPI.dll file. (e.g.: .asp files should map to the %windir%system32inetsrvasp.dll file)

Option #3: HRESULT: 0x8007007f – There is a problem with the resource you are looking for, so it cannot be displayed. This occurs because the handler mapping for the requested resource points to a .dll file that cannot process the request.

Resolution would be to edit the handler mapping for the requested resource to point to the .dll file that can process the request. To do this, follow these steps:

Click Start, click Run, type inetmgr.exe, and then click OK.
In IIS Manager, expand server name, expand Web sites, and then click the Web site that you want to modify.
In Features view, double-click Handler Mappings.
Right-click the script mapping that you want to edit, and then click Edit.
In the Edit Script Map dialog box, type the appropriate executable file in the Executable box, and then click OK.

Option #4: One of the other possibilities could be an issue in the way web application is hosted. Some security configuration issue or conflict due to multiple config files.

Resolution would be to make sure application is hosted correctly by published the application as website and setting up the virtual directory as needed.

BGeorge

2 / 2 / 0

Регистрация: 07.07.2016

Сообщений: 52

1

08.08.2016, 19:24. Показов 4934. Ответов 3

Метки 500, ajax, javascript, php (Все метки)


Ну у меня уже давно голова кипит. В общем, я не знаю в чем проблема:

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$("#login .regForm input[name=registration]").click(function () {
            $("#login .regForm .textError").html("");
            var login = $("#login .regForm input[name=login]").val();
            var password = $("#login .regForm input[name=password]").val();
            var r_password = $("#login .regForm input[name=r_password]").val();
            var email = $("#login .regForm input[name=email]").val();
            if (password == r_password && r_password !== "") {
                $.ajax ({
                    url: "login/registration.php",
                    type: "POST",
                    data: ({login: login, password: password, email: email}),
                    dataType: "html",
                    success: function (data) {
                        if (data == "loginError1") {
                            $("#login .regForm .regErrorLogin").html("Не менее 3х символов");
                        }
                        if (data == "loginError2") {
                            $("#login .regForm .regErrorLogin").html("Не более 20ти символов");
                        }
                        if (data == "passError1") {
                            $("#login .regForm .regErrorPass").html("Не мение 5ти символов");
                        }
                        if (data == "passError2") {
                            $("#login .regForm .regErrorPass").html("Не более 20ти символов");
                        }
                        if (data == "emailError") {
                            $("#login .regForm .regErrorEmail").html("Не корректная почта");
                        }
                        if (data == "okay") {
                            
                        }
                    }
                });
            } else if (password == "") {
                $("#login .regForm .regErrorPass").html("Введите пароль");
            } else {
                $("#login .regForm .regErrorR_pass").html("Пароли не совпадают");
            }
        });

Но тут php такая история. Если просто вывести echo, то вроде все нормально. Но так — нет :

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
    
    $login = $_POST['login'];
    $password = $_POST['password'];
    $email = $_POST['email'];
 
    $strLogin = string($login);
    $strPass = string($password);
 
    if ($strLogin < 3) {
        echo "loginError1";
    }
    if ($strLogin) > 20) {
        echo "loginError1";
    }
    if ($strPass < 5) {
        echo "passError1";
    }
    if ($strPass > 20) {
        echo "passError1";
    }
 
 
?>

jquery.min.js:4 POST http://localhost/minakoff/login/registration.php 500 (Internal Server Error)

Добавлено через 3 минуты
я все исправил. Как удалить тему?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



insideone

10.08.2016, 00:58

Не по теме:

Цитата
Сообщение от BGeorge
Посмотреть сообщение

я все исправил. Как удалить тему?

п2.3 правил: Сообщения и темы, а также другой контент, размещаемый на форуме, по просьбам пользователей не удаляется и не закрывается.



0



618 / 216 / 51

Регистрация: 22.11.2010

Сообщений: 1,776

Записей в блоге: 3

10.08.2016, 01:24

3

Цитата
Сообщение от BGeorge
Посмотреть сообщение

я все исправил. Как удалить тему?

Мсье, если вы исправили ошибку, то расскажите в чем была проблема. Возможно кому-то в будущем это спасет жизнь!



0



2 / 2 / 0

Регистрация: 07.07.2016

Сообщений: 52

10.08.2016, 09:15

 [ТС]

4

ОТВЕТ
Проблема в том, что эта ошибка высвечивается если в коде php допущена серьезная ошибка. К примеру, не закрыли скобки у условного оператора или еще какая-нибудь ошибка, из-за которой не загружается страница с кодом.



1



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Get 404 ошибка
  • Get 304 error
  • Gestao de energia монитор как исправить
  • Gepard 12 mtv ошибка f62
  • Geometry dash системная ошибка

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

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