Search code examples
phpajaxlaravelhttp-redirectcsrf

How to redirect back with errors in Laravel 8 inside an Ajax request


When data.custom_input === "false" I want to redirect back with errors. redirect()->back() is giving me this error inside the console: Uncaught SyntaxError: Unexpected number: cd988e2f-ba9c-4b66-97d9-618e776ae740:157. Which is my uuid I pass to all routes.

URL::previous does work fine, but I can't pass any errors.

let interval = 1000;

function doAjax() {
$.ajax({
    type: 'POST',
    url: '/listen/custominput',
    data: {
        '_token': $('meta[name="csrf-token"]').attr('content')
    },
    dataType: 'json',

    success: function (data) {
        if (data.custom_input === "true") {
            window.location.href = "{{route('index', $link->id)}}";

        } else if (data.custom_input === "false") {
            window.location.href = {{redirect()->back()->withErrors(['error', 'has-error'])}};
        }
    },

    complete: function (data) {
        setTimeout(doAjax, interval);
    }
});
}
setTimeout(doAjax, interval);

What do I need to do?


Solution

  • Instead of your (POST) route returning custom_input = "false" and then trying to redirect back in JavaScript, you should redirect in the (POST) route controller (not in blade/js) with what you already have:

    redirect()->back()->withErrors(['error', 'has-error'])