Просмотр не обновляется после перенаправления - PullRequest
0 голосов
/ 24 июня 2019

Я разрабатываю простое приложение для покупки билетов с помощью Laravel.

У меня проблемы с обновлением представления после того, как пользователи выбрали билеты для покупки, где не имеет значения, какой тип перенаправления я использовал в ajaxRequestPost, представление по-прежнему застряло на / вместо перенаправить на платежей / {идентификатор} .

Однако я получил возврат файла payment.index , но представление не обновилось до возвращенного содержимого.

Код BitBucket: https://bitbucket.org/naimrahidin/laravel_ticketing/src/master/

маршруты / web.php

Route::resource('/', 'TicketController');
Route::post('createOrder', 'OrderController@ajaxRequestPost');
Route::get('/payments/{id}', 'PaymentController@show');

TicketController.php

public function index(){
        $tickets = Ticket::all();

        return view('tickets.index', compact('tickets'));
    }

OrderController.php

public function ajaxRequestPost(Request $request)
{
    $input = $request->all();

    for($i = 1; $i < 4; $i++){
        if($input['ticket_'.$i.'_q'] != 0) {

            $spkAdmin = new Order();
            $spkAdmin->ticket_id = $i;
            $spkAdmin->quantity = (int)$input['ticket_'.$i.'_q'];
            $spkAdmin->total = (int)$input['ticket_'.$i.'_t'];
            $spkAdmin->user_id = $input['user_id'];
            $spkAdmin->save();

            $orders = array(
                'id' => $i,
                'quantity' => (int)$input['ticket_'.$i.'_q'],
                'total' => (int)$input['ticket_'.$i.'_t']
            );
        }
    }

    return redirect()->action(
        'PaymentController@show', ['id' => $input['user_id']]
    );
}

PaymentController.php

public function show($id)
{
    $orders = DB::table('orders')->where('user_id', $id)->get();

    return view('payments.index', ['orders' => $orders]);
}

платежи / index.blade.php

@extends('base')

@section('main')
<div class="row">
    <div class="col-sm-12">
        <h1 class="display-3">Payments</h1>
        <h3 class="display-5" data-user-id="1">Naim Rahidin</h3>
        <table class="table table-striped">
            <thead>
                <tr>
                    <td>Ticket ID</td>
                    <td>Quantity</td>
                    <td>Total</td>
                </tr>
            </thead>
            <tbody>
                @foreach($orders as $order)
                <tr>
                    <td>{{$order->ticket_id}}</td>
                    <td>{{$order->quantity}}</td>
                    <td>{{$order->total}}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
        <div class="order_detail">
            <p>Total: RM <span id=grand_total>0</span></p>
            <p id="proceed" class="btn btn-primary">Checkout</p>
        </div>
    </div>
</div>
@endsection

Ответы [ 2 ]

0 голосов
/ 24 июня 2019

Разобрался с ответом для этого.

Так как я вызываю createOrder через Ajax, OrderController должен отправить обработанное представление как ответ, а в ajax.success должен заменить html.

добавлено в OrderController.php

$html = view('payments.index')->render();
$response = response()->json(['success' => true, 'html' => $html]);
return $response;

ajax

success: function(data) {
    $('.container').html(data.html);
}
0 голосов
/ 24 июня 2019

Привет, я думаю $input['user_id'] этот идентификатор не является int его strint, пожалуйста, преобразуйте в int за использование type casting например, используйте (int) начало переменной и попробуйте этот код

return redirect()->action( 'PaymentController@show', ['id' => (int)$input['user_id']] );

checkout.js file

        $.ajax({
            type: 'POST',
            url: '/createOrder',
            data: {
                ticket_1_q: ticket_1_q,
                ticket_2_q: ticket_2_q,
                ticket_3_q: ticket_3_q,
                ticket_1_t: ticket_1_t,
                ticket_2_t: ticket_2_t,
                ticket_3_t: ticket_3_t,
                user_id: 1
            },
            dataType: 'json',
            success: function(data) {
                if (data.status == 200) {
                    window.location.href = data.data;
                }
            },
            error: function(xhr, ajaxOptions, thrownError){
                alert(thrownError);
            },
        });

Контроллер заказа

    public function ajaxRequestPost(Request $request)
{
    $input = $request->all();

    for($i = 1; $i < 4; $i++){
        if($input['ticket_'.$i.'_q'] != 0) {

            $spkAdmin = new Order();
            $spkAdmin->ticket_id = $i;
            $spkAdmin->quantity = (int)$input['ticket_'.$i.'_q'];
            $spkAdmin->total = (int)$input['ticket_'.$i.'_t'];
            $spkAdmin->user_id = $input['user_id'];
            $spkAdmin->save();

            $orders = array(
                'id' => $i,
                'quantity' => (int)$input['ticket_'.$i.'_q'],
                'total' => (int)$input['ticket_'.$i.'_t']
            );
        }
    }
        $url = "/payments/".$input['user_id'];
        return response()->json([
            'status'=>200,
            'message'=>"done",
            'data'=> $url
        ]);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...