display flash and error message after ajax request Laravel
Asked Answered
D

3

6

After a successful ajax request, I want to send a flash message to my view (For example, upon editing, I'd like to redirect the user to the homepage with $flash = "Your shop has been update" ). Within the controller, it is easy but I don't know what to do within JavaScript. Do any of you know how to figure it out? Im using Laravel

Controller

   public function postUpdate (Request $request)
    {
            $this->validate($request, [
                'website_name' => 'required',
                'website_url' => 'required',
                'category' => 'required',
                'type' => 'required',
                'sells' => 'required',
                'location' => 'required',
                'description' => 'required',
                'payment' => 'required'
            ]);
            Shop::where('username', '=', Auth::user()->username)->update(['website_name' => Input::get('website_name'),
                'website_url' => Input::get('website_url'), 'type' => Input::get('type'), 'category' => Input::get('category'), 'sells' => Input::get('sells'), 'location' => Input::get('location'),
                'payment' => Input::get('payment'), 'description' => Input::get('description')]);
        return Response::json(['message' => 'Success', 'message_class' => 'alert alert-success fade in']);
    }

AJAX

$(".update-form").submit(function(s){

            s.preventDefault();

            var website_name = $('input[name=website_name]').val();
            var website_url = $('input[name=website_url]').val();
            var type = $('#type option:selected').val();
            var category = $('#category option:selected').val();
            var sells = $('input[name=sells]').val();
            var location = $('input[name=location]').val();
            var payment = $('input[name=payment]').val();
            var description = $("textarea#message").val();

                $.ajax({
                type: "POST",
                url: "advertiser/update",
                data: {
                    _token: token, website_name: website_name, website_url: website_url, type: type, category: category, sells: sells, location: location, payment: payment, description: description

                },

                success: function() {
                   $('.modal-backdrop').remove();
                    $('body').load('advertiser')

                },

                error: function(data) {
                    $('body').load('advertiser')

                }
                      })


        });

HTML

  <div class="row" id="errors">
            @if (Session::has('message'))
                <div class="{!! Session::get('message_class') !!}">
                    <a href="#" class="close" data-dismiss="alert">&times;</a>
                    <strong>Note!</strong> {!! Session::get('message') !!}
                </div>
            @endif

            @if($errors->has())
                <div class="alert alert-danger fade in">
                    <a href="#" class="close" data-dismiss="alert">&times;</a>

                    <p>the following errors have occured:</p>
                    <ul>
                        @foreach($errors->all() as $error)
                            <li>{{$error}}</li>
                        @endforeach
                    </ul>
                </div>

            @endif
Dunnite answered 13/11, 2015 at 12:10 Comment(4)
You want to redirect the page after ajax result is received ?Grandmother
no i already change to Respone::json I want to know how to get the data in javascript(jquery) @sulthanAllaudeenDunnite
@Juam Posted the answer, You want the full script in Jquery ?Grandmother
Possible duplicate of Session::flash not working in ajax laravel 5Rhapsodize
G
4

You can't redirect the within controller if you use ajax request.

But you can do like this.

Send some parameters in the Controller like this

$Response   = array(
            'success' => '1',
        );

or

$Response   = array(
            'success' => '0',
            'error' => 'Your Flash Message'
        );

and return it return $Response;

Then, In the ajax result you can redirect the user like this

if (data.success == 1){
    window.location = 'toyourdesiredpath';
}
else
{
//show your error message in your div or span
}
Grandmother answered 13/11, 2015 at 12:38 Comment(1)
This won't display the message though, you will still need to set the session.Conspectus
T
1

Just set a session flash message and a redirect url in Laravel controller (or return null if you want to reload the current page) like this:

if ($redirect) {
    session()->flash('success', 'Your Flash Message for redirect');
    return '/redirect-url';
} else {
    session()->flash('success', 'Your Flash Message for reload');
    return null;
}

And then make the redirect or reload inside the JavaScript code:

$.post(`/ajax-url`, $(e.target).serialize()
  ).done((redirect) => {
    if (redirect) {
      window.location.href = redirect
    } else {
      window.location.reload()
    }
  }).fail((errors) => {
    this.setState({
      errors: errors.responseJSON.errors
    })
  })
Titanic answered 13/12, 2018 at 17:37 Comment(2)
Works to me. ThanksMenell
Did not work for me. I am using laravel 8.*.Elf
L
-2

You have to use redirect with message, try following example in your code :-

return Redirect::to('user/login')->with('message', 'Login Failed');

Legitimist answered 13/11, 2015 at 12:13 Comment(4)
return Redirect::to('advertiser')->with(['message' => 'Success', 'message_class' => 'alert alert-success fade in']); not working if I remove ajax its working...Dunnite
do one thing return some status as json and then in success of ajax you can display that success messageLegitimist
return Response::json or return json_encode I dont know how to get it using javascript can u give me an example please thank you :)Dunnite
Here you can find more relevant answer for you :- #15624575Legitimist

© 2022 - 2024 — McMap. All rights reserved.