Jquery post 500 internal server error

Ответили на вопрос 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

Nov 11, 2021 . Admin

Hi Dev,

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 fix 500 (internal server error) ajax post 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

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

You might also like…

  • Laravel 8 Autocomplete Search using Typeahead JS Example Tutorial
  • Laravel 8 Ajax Image Upload Example
  • Laravel 8 Ajax Form Validation Example
  • Laravel 8 Ajax Autocomplete Search from Database Example
  • Laravel 8 Redirect User to Previous Page After Login
  • How To Handle «No Query Results For Model» Error — Laravel 8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@moritzwelsch

I implemented your example in my Project, but now i cant send any messages.

jquery.js:8625 POST http://localhost:8000/ajax/message/send 500 (Internal Server Error)
send @ jquery.js:8625
ajax @ jquery.js:8161
(anonymous) @ talk.js:16
dispatch @ jquery.js:4430
r.handle @ jquery.js:4116

@moritzwelsch
moritzwelsch

changed the title
jquery.js:8625 POST http://localhost:8000/ajax/message/send 500 (Internal Server Error)

POST http://localhost:8000/ajax/message/send 500 (Internal Server Error)

Jan 16, 2017

@ed-i-arellano

I have the same error when I send a message.

@nahid

please share your code with me.

@kingsleyzissou

I had the same issue. I found that the auth::user() wasn’t being set (I’m using Laravel 5.4).
What sorted it out for me was adding the following to the constructor of my controller:

$this->middleware(function ($request, $next) { Talk::setAuthUserId(Auth::user()->id); return $next($request); });

Hope that helps!

@ElBetito

@jbhoomi89

Thanks It works fine!
It also solved trying to get property on non object error for me..
Thank you soo much!!

@marslan2037

@kingsleyzissou

@marslan2037 you place it inside the constructor and delete the line

Talk::setAuthUserId(Auth::user()->id);

So your constructor should look like this:

public function __construct()
{
    $this->middleware('auth');

    View::composer('partials.peoplelist', function($view) {
        $threads = Talk::threads();
        $view->with(compact('threads'));
    });

    $this->middleware(function ($request, $next) {
        Talk::setAuthUserId(Auth::user()->id);
        return $next($request);
    });
}

@marslan2037

@marslan2037

500 interval server error

@marslan2037

@kingsleyzissou this is what in preview tab
No connection could be made because the target machine actively refused it. [tcp://127.0.0.1:6379]

@kingsleyzissou

@marslan2037 that’s a different issue, it sounds like you need to setup redis on your computer and update the .env file with the correct information

@marslan2037

@marslan2037

i update everything with pusher info

@marslan2037

in env file and in talk.php also

@marslan2037

preview tab shows this error, console shows 500 interval server error with message/send route

@marslan2037

@kingsleyzissou i am using talk example, i did not add anything new in it, just did one change that have mention but same error, with and without that change

@kingsleyzissou

@marslan2037 this issue is closed, the issue you’re having is unrelated.

[tcp://127.0.0.1:6379] -> port 6739 is used for redis
You can go here for more info https://redis.io/

If you get redis setup on your machine it should resolve the issue.

@marslan2037

@kingsleyzissou ok, but i did not install anything new in it, if package did not have it then i have it, let me reclone it and try again

@marslan2037

@alamintpi

i am same problem here……..plz help me

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 json syntax error
  • Jquery img load error
  • Jquery image load error
  • Jquery get fail error
  • Jquery get error message