jeudi 27 août 2015

Laravel 5: How do I display a message and redirect after an Ajax post

I have a simple blog post page that is submitting data through ajax jquery. It works fine, but at the moment, it returns the json response after submission.

What I need it to do is display the success message to the user on the submit page and then redirect him to the main articles page.

If I comment out return Response::json($response); I get a blank page but I don't wanna redirect him to another view automatically, I want to show him a message for 5 seconds and then redirect him.

And $("#ajaxResponse").append(msg); isn't doing anything.

This is my controller

public function store(Requests\ArticleRequest $request)
    {

        $article = new Article($request->all());
        Auth::user()->articles()->save($article);

        $response = array(
            'status' => 'success',
            'msg' => 'Setting created successfully',
        );

        return \Response::json($response);
    }

This is AJAX request

$(document).ready(function() {
    $('#submit').on('submit', function (e) {
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: host + '/articles/create',
            data: {title: title, body: body, published_at: published_at},
            success: function( msg ) {
                $("#ajaxResponse").append(msg);
            }
        });
    });
});

And this is the view

<link rel="stylesheet" href="http://ift.tt/1K1B2rp">

<h1>Write a New Article</h1>

<hr>

{!! Form::open(['url' => 'articles']) !!}
    <p>
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title') !!}
    </p>

    <p>
        {!! Form::label('body', 'Body:') !!}
        {!! Form::textarea('body') !!}
    </p>

    <p>
        {!! Form::label('published_at', 'Date:') !!}
        {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
    </p>

    <p>
        {!! Form::submit('Submit Article', ['id' => 'submit']) !!}
    </p>
{!! Form::close() !!}

<h3 id="ajaxResponse"></h3>

@if($errors->any())
    <ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KQuE34
via IFTTT

Aucun commentaire:

Enregistrer un commentaire