Jquery ajax post error 500

Ответили на вопрос 4 человека. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.

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

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

Я новичок в AJAX, и я просто пробовал некоторые примеры AJAX, но я получаю эту 500 Внутренняя ошибка сервера. Я ищу в Интернете решение, но ничего не получается. Тем не менее, если я изменить тип с POST на GET, он работает нормально.

контроллер:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class testingAjax extends CI_Controller
{
public function index()
{
$this->load->view('testingAjax_view');
}

public function getSomething()
{
$values = $this->input->post('testing');
echo $values;
}
}

JS скрипт

$(document).ready(
function ()
{
$('#callBackBtn').click(function()
{
jQuery.ajax({
type: "POST",
url: "testingAjax/getSomething",
data: {testing: "testing"},
success: function(data) {
$('#responseText').val(data);
},
error: function(xhr, text_status, error_thrown){
alert(error_thrown);
}

})
});
}
);

Посмотреть

<body>
<h3>Testing Ajax</h3>
<div class="entry-wrapper">
<input type="text" id="input_text">
<input type="button" value="Ajax Call Back" id="callBackBtn"/>
</div>
<div class="response_wrapper">
<textarea id="responseText"></textarea>
</div>
</body>

Я запускаю это на xammp. Ниже приведены журналы ошибок Apache (не уверен, полезны они или нет)

[Wed May 13 00:31:53.251642 2015] [core:notice] [pid 25716:tid 456] AH00094: Command line: 'c:\xampp\apache\bin\httpd.exe -d C:/xampp/apache'
[Wed May 13 00:31:53.257646 2015] [mpm_winnt:notice] [pid 25716:tid 456] AH00418: Parent: Created child process 25724
[Wed May 13 00:31:57.895294 2015] [ssl:warn] [pid 25724:tid 460] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Wed May 13 00:31:59.065692 2015] [ssl:warn] [pid 25724:tid 460] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Wed May 13 00:31:59.205786 2015] [mpm_winnt:notice] [pid 25724:tid 460] AH00354: Child: Starting 150 worker threads.

Firebug показал ошибку:

POST http://localhost/ias/testingAjax/getSomething
500 Internal Server Error
30ms

1

Решение

Попробуй с

url:"/testingAjax/getSomething".

Для вызова ajax метод по умолчанию GET а ты не публиковал form или любое значение для сервера, просто сделать ajax-вызов по нажатию кнопки, поэтому это может сработать !!! когда вы изменили тип метода с POST в GET но прежде всего я думаю, что вы должны исправить url

Метод (по умолчанию: «GET»)

Тип: String Метод HTTP, используемый для

запрос (например, «POST», «GET», «PUT»)

увидеть больше здесь http://api.jquery.com/jquery.ajax/

1

Другие решения

Я создал свежую копию вашей работы, а здесь простую, которой вы могли бы следовать.

Во-первых, правильно настроить ваш проект.

Сначала я создаю файл .htaccess в корневой папке той же директории, что и index.php, чтобы создать красивый URL

Вот простой файл содержимого .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
</IfModule>

И вам нужно включить расширение / настройку mod_rewrite вашего сервера

Вы можете включить его, найдя appache / httpd.conf

и найдите «LoadModule rewrite_module modules / mod_rewrite.so»

удалите # и сохраните и перезапустите приложение.

Следующим шагом является включение помощника URL

на

приложение / Config / autoload.php

$autoload['helper'] = array('url');

использовать url helper, созданный CI;

Увидеть URL HELPER

Далее нужно настроить контроллер по умолчанию, чтобы сделать это
приложение / Config / routes.php

$route['default_controller'] = 'testingAjax';

Контроллер testingAjax.php

<?php

class testingAjax extends CI_Controller
{
public function index()
{
$this->load->view('testingAjax_view');
}

public function getSomething()
{
$values = $this->input->post('testing');
echo $values;
}
}

Представление testingAjax_view.php

<html>
<head>
<script type="text/javascript">
// get the base url of the project
var BASE_URL = "<?php echo base_url(); ?>";
</script>
</head>
<body>
<h3>Testing Ajax</h3>

<div class="entry-wrapper">
<input type="text" id="input_text">
<input type="button" value="Ajax Call Back" id="callBackBtn"/>
</div>

<div class="response_wrapper">
<textarea id="responseText"></textarea>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready( function() {

$('#callBackBtn').on('click', function(){
$.ajax({
type: "POST",
url: BASE_URL + "testingAjax/getSomething",
data: {testing: $('#input_text').val()},
success: function(data) {
$('#responseText').val(data);
},
error: function(xhr, text_status, error_thrown){
alert(error_thrown);
}

});

// But if you cannot setup the pretty url
// using .htaccess
// then you can use the
// BASE_URL+ "index.php/" + "testingAjax/getSomething
});
});

</script>

</body>

</html>

1

Просто поместите это в ваш файл .htaccess, который находится в вашем корневом каталоге:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Замечания:

RewriteBase / здесь важно

0

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

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.

Понравилась статья? Поделить с друзьями:
  • Jquery ajax json error
  • Jquery ajax error пример
  • Jquery ajax error php
  • Jquery ajax error message
  • Jquery ajax error internal server error