Я из базы достаю записи определенного пользователя. При желании пользователь может оставить комментарий к записи. Есть кнопка «Добавить комментарий», при нажатии на которую вываливается 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')
В чем может быть проблема?
This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.
Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:
$.ajax({ url: 'does-not-exist.php', success: function(returnData){ var res = JSON.parse(returnData); }, error: function(xhr, status, error){ var errorMessage = xhr.status + ': ' + xhr.statusText alert('Error - ' + errorMessage); } });
If you look at the code above, you will notice that I have two functions:
- success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
- error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.
The Ajax error function has three parameters:
- jqXHR
- textStatus
- errorThrown
In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:
- status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
- statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.
Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.
JQuery 3.0: The error, success and complete callbacks are deprecated.
Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.
An example of done and fail being used:
$.ajax("submit.php") .done(function(data) { //Ajax request was successful. }) .fail(function(xhr, status, error) { //Ajax request failed. var errorMessage = xhr.status + ': ' + xhr.statusText alert('Error - ' + errorMessage); })
Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.
Hopefully, you found this tutorial to be useful.
Можете ли вы опубликовать подпись своего метода, который должен принять этот пост?
Кроме того, я получаю такое же сообщение об ошибке, возможно, по другой причине. Мой 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>
так что проверьте все это и опубликуйте подпись своего контроллера в случае, если часть проблемы
You sometimes get a jQuery Ajax Error 500. The Homestead /var/logs/error.log will show you nothing and in your laravel.log nothing shows either. Fortunately in your console you did get an error and as it is a JavaScript or to be specific a jQuery Ajax error. So that is a start. But how to get to the bottom of this?
Background Information
As a heads up here some background information. We are using a Laravel Transip Package by Hidde. It is used to connect to a service provider (Transip) via a Soap API. And we use jQuery Ajax calls to make requests to this interface. We are working locally on a Laravel Homestead box and bumped into this error 500 issues and decided to dive deep into this package and the API provided by the service provider.
General jQuery Error
At first you will see the general error message and what functions it is related to (code modified somewhat names wise):
GET http://domain.test/backend/check-availability?querystring=value 500 (Internal Server Error) send @ jquery.min.js:4 ajax @ jquery.min.js:4 checkSomethingAvailability @ something-management?project=97:503 onclick @something-management?project=97:307
jQuery Send Error
With the JS beautified you can go to the line where the error occured. In this case line 4208 of jQuery formatted:
jquery.min.js:formatted:4208 GET http://domain.test/dashboard/check-domain-availability?domain=domain.io 500 (Internal Server Error) send @ jquery.min.js:formatted:4208 ajax @ jquery.min.js:formatted:3990 checkDomainAvailability @ domain-management?project=97:503 onclick @ domain-management?project=97:307
There you can see
g.send(b.hasContent && b.data || null)
and a cross next to it. When you hover on it you see this message
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
So sending the data it failed to load something.
SoapFault
Then you decide to check the response for the actual file in the console by clicking the file under the Network Tab (Chrome Inspector):
That shows an exception. One that was not logged in the error log…. And there appears to be a SoapFault as you can see.
The actual error is this one:
(1/1) SoapFault Exception received from JSON Server: Timestamp outside maximum allowed window of 15 minutes; given timestamp was: 1518507112 (timestamp: 0.13471400 1520058610) in AbstractApi.php (line 36) at SoapClient->__call('checkAvailability', array('domain.com')) in AbstractApi.php (line 36) at AbstractApi->call('domainService', 'checkAvailability', array('domain.com')) in Domain.php (line 20) at Domain->checkDomain('domain.com') in DomainManagementController.php (line 81) at DomainManagementController->checkAvailability(object(Request), object(DomainManager)) at call_user_func_array(array(object(DomainManagementController), 'checkAvailability'), array(object(Request), object(TransIPManager))) in Controller.php (line 55) at Controller->callAction('checkAvailability', array(object(Request), object(TransIPManager))) in ControllerDispatcher.php (line 44) at ControllerDispatcher->dispatch(object(Route), object(DomainManagementController), 'checkAvailability') in Route.php (line 203) .......
AbstractApi Call
in AbstractApi.php of the Laravel package in question on line 36 mentioned in the error report we have
protected function call($service, $method, array $parameters = []) { return$this->getSoapClient($service, $method, $parameters)->__call($method, $parameters); }
which is called from Domain.php with this function
public function checkAvailability($domainName) { return$this->call(self::SERVICE, 'checkAvailability', [$domainName]); }
JSON Server Exception
The Laravel API Package throws a SoapFault every time there is an issue making a connection. The username and key should be fine. I checked. The exception:
Exception received from JSON Server: Timestamp outside maximum allowed window of 15 minutes; given timestamp was: 1518507112 (timestamp: 0.13471400 1520058610)
Timezone Solution
Perhaps a timezone issue as Thomas at the Facebook PHP Group suggested. Logical when I think about it now, but well. So I did a
ln -sf /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime
inside after.sh to make it Amsterdam time like the hoster, but it did not pick it up. And the Homestead date was February the 13th which was also completely off.
However when I did a:
sudo timedatectl set-timezone Europe/Amsterdam
inside the Vagrant Box and a hard reboot I got where I wanted to be. It did force me to do a service nginx restart
vagrant@homestead:~$ service nginx restart ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units === Authentication is required to restart 'nginx.service'. Authenticating as: vagrant,,, (vagrant) Password: ==== AUTHENTICATION COMPLETE ===
to get things going.. However I go the CET time and correct date:
date Sat Mar 3 12:25:46 CET 2018
And once I had that all started working!
NB Funnily the Box was set to ‘timezone’ => ‘Europe/Amsterdam’, in config/app.php already..
In this post we will show you how to jQuery ajax error function when Ajax decision passing information to a page that then returns a worth(value).
I have retrieved the self-made decision from the page however I even have coded it so it raises an erreo(bug) within the your call page(example url: "data.php"
). however do we retrieve that error from the jquery? how we get jQuery Ajax Error Handling Function hear is the solution of ajax error function.
this jQuery ajax error function is very basic and easy to use with your ajax call.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data) { // success alert message alert(data); }, error: function (error) { // error alert message alert('error :: ' + eval(error)); } });
jQuery ajax error function using jqXHR
jQuery ajax error function using jqXHR in this function we can get different type ajax error like 404 page error, 500 Internal Server error, Requested JSON parse, Time out error.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data) { // success alert message alert(data); }, error: function (jqXHR, exception) { var error_msg = ''; if (jqXHR.status === 0) { error_msg = 'Not connect.n Verify Network.'; } else if (jqXHR.status == 404) { // 404 page error error_msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { // 500 Internal Server error error_msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { // Requested JSON parse error_msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { // Time out error error_msg = 'Time out error.'; } else if (exception === 'abort') { // request aborte error_msg = 'Ajax request aborted.'; } else { error_msg = 'Uncaught Error.n' + jqXHR.responseText; } // error alert message alert('error :: ' + error_msg); }, });
Parameters for jQuery ajax error function with jqXHR
Parameters for jQuery ajax error function with jqXHR for It actually an error object which is looks like this.
jQuery ajax error function with an validation error
jQuery ajax error function with an validation error :: If we want to inform(get error message) in frontend about an validation error try this method.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data, textStatus, jqXHR) { console.log(data.error); } });
Я новичок в 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