0

Не первый раз обращаюсь к formData уже, и каждый раз не получается, решил еще раз, ума не приложу, что сделал не так:

            <form id="rate" name="rate" action="/apps/rate" method="POST">
                @csrf
                <input type="hidden" name="id" value="{{ $app->id }}">
                <fieldset class="rating">
                    <input type="radio" id="star5" name="rating" value="5" /><label class = "full" for="star5" title="Awesome - 5 stars"></label>
                    <input type="radio" id="star4half" name="rating" value="4.5" /><label class="half" for="star4half" title="Pretty good - 4.5 stars"></label>
                    <input type="radio" id="star4" name="rating" value="4" /><label class = "full" for="star4" title="Pretty good - 4 stars"></label>
                    <input type="radio" id="star3half" name="rating" value="3.5" /><label class="half" for="star3half" title="Meh - 3.5 stars"></label>
                    <input type="radio" id="star3" name="rating" value="3" /><label class = "full" for="star3" title="Meh - 3 stars"></label>
                    <input type="radio" id="star2half" name="rating" value="2.5" /><label class="half" for="star2half" title="Kinda bad - 2.5 stars"></label>
                    <input type="radio" id="star2" name="rating" value="2" /><label class = "full" for="star2" title="Kinda bad - 2 stars"></label>
                    <input type="radio" id="star1half" name="rating" value="1.5" /><label class="half" for="star1half" title="Meh - 1.5 stars"></label>
                    <input type="radio" id="star1" name="rating" value="1" /><label class = "full" for="star1" title="Sucks big time - 1 star"></label>
                    <input type="radio" id="starhalf" name="rating" value="0.5" /><label class="half" for="starhalf" title="Sucks big time - 0.5 stars"></label>
                </fieldset>
            </form>

Сама форма:

        <script>
            $('.rating input').on('click', function() {
                var url = '/apps/rate';
                var formData = new FormData($('#rate'));
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                 $.ajax({
                    url: url, 
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        console.log(response['ip']);
                    }
                });        
            });
        </script>

И контроллер:

public function rate(Request $request) {
    $ip = $request->ip();
    $ip = ip2long($ip);
    $comments = Apps::find(2)->votes()->get();
    return response()->json([
        'success' => true,
        'ip' => json_decode($request->getContent()),
    ]);

Все это дело на laravel. Подскажите пожалуйста, для меня formData сущая пытка, я перечитал все уже, толку 0

2 ответа 2

1

Попробуйте передать формдате конкретный элемент $('#rate')[0].

Или попробуйте добавить нужные параметры через formData.append.

Вы уверены, что контроллер у вас без расширения? var url = '/apps/rate';

1
  • ну еще бы я контроллер криво сделал))) тут проблема в том, что у меня formData судя по всему вообще пустой, я как-то криво туда инфу пихаю, если снести ее и указать свои переменные. все отлично
    – Paul Wall
    19 мар 2018 в 20:23
0

К сожалению не большой знаток JS, но в аналогичной ситуации прописал следующее: Параметры $.ajax заполнил так

type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
cache: false,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 

В данном случае var form = $('#form'); - получение данных с формы.

На сервер уходит запрос, который корректно распознает $_POST. Он имеет вид

item1=80&street=str_name

т.е. пара ключ/значение. Посмотреть формат отправляемого запроса можно вызвав console.log(form.serialize());

Ответ возвращал в виде Json. Соответственно console.log(response.msg);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.