1

So, I've noticed that as of the last version 5.6 Laravel returns the server side exceptions in a json format instead of html when handling ajax POST requests. This is a genuine problem for my developed debugging logic from the previous version, as I've counted on laravel returning a rendered HTML page of the error as the .responseText of the response, so I could easily display the whole content in a new window and see it clearly (for debugging purposes). What happens now is basically the following:

  • .$ajax() POST request is being sent to the server;
  • some serverside php error occurs in the function handling the response (say, unknown variable for example)
  • so the ajax error function of the request receives its first argument (xhr), which is as of right now a JSON array with the following structure: enter image description here
  • now I'd like to display that message in a new window, but with the rendered HTML layout that Laravel usually provides and I really like

I really wouldn't want to have to begin building the html look all by my own when I already know, that Laravel could render it for me. The problem is that I couldn't find recent documentations on the topic, nor a proper way to return a rendered html content as a response. So my question is, could anyone advise me as of what is the best alternative of rendering the html content? Which method is the best way of receiving what I want and is there still any particular such method? Thansk in advance!

Edit Here's my ajax request:

$.ajax({
    method: "POST",
    url: '/updateModel',
    data: dataObject,
    success: success
});

Where dataObject is really only the contained data for the request. What I've got in my initial .js file though is the following:

$(function () {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $(document).ajaxStart(function() {
                showGlobalLoader(true); //shows the loader
            })
            .ajaxStop(function() {
                showGlobalLoader(false); //hides the loader
            })
            .ajaxError(ajaxErrorGlobalFunction); //displays the new window - that's the function in question
        });

And then that's the ajaxErrorGlobalFunction function

function ajaxErrorGlobalFunction(xhr, status, error) {
    if (xhr.responseText) {
        //console.log(xhr.responseText);
        openErrorWindow(xhr.responseJSON);
    }
}


function openErrorWindow(json = "")
{
    var w = window.open('', '_blank', 'scrollbars=no,status=no,titlebar=no');
    $(w.document.body).html(json.message + "\n in file " + json.file + "\n on line " + json.line);
    w.resizeTo(1000, 1000);
    w.moveTo(0, 0);
    w.focus();
}

As you can see, I used to just render the xhr.responseText as the html content of the window, but now I got forced to work it around by extracting the most important information from the json. I'd really like to have the good old html content back as a response of the request. Thanks in advance!

2
  • Can you show us your ajax post request? Normally when you don't want a json, Laravel doesn't return a json. Commented May 16, 2018 at 12:56
  • @ChinLeung I've edited my post with all the code I could come up with that's related to the topic. If I've forgotten something, excuse me! I'll add it if needed. Commented May 17, 2018 at 7:38

1 Answer 1

1

As you can see in the exceptions handler (Illuminate/Foundation/Exceptions/Handler.php:185):

return $request->expectsJson()
    ? $this->prepareJsonResponse($request, $e)
    : $this->prepareResponse($request, $e);

If the request wants a json as response, it will convert it to json, otherwise it will render it as it used to.

Add a dataType to your Ajax request that isn't json and this should work:

$.ajax({
    method: "POST",
    url: '/updateModel',
    data: dataObject,
    dataType: 'html',
    success: success
});

Update

If you want to always display the exceptions as HTML, you can update the render function of the exception handler (app/Exceptions/Handler.php) by copying the parent's render function and remove the expectsJson ternary:

if (method_exists($e, 'render') && $response = $e->render($request)) {
    return Router::toResponse($request, $response);
} elseif ($e instanceof Responsable) {
    return $e->toResponse($request);
}

$e = $this->prepareException($e);

if ($e instanceof HttpResponseException) {
    return $e->getResponse();
} elseif ($e instanceof AuthenticationException) {
    return $this->unauthenticated($request, $e);
} elseif ($e instanceof ValidationException) {
    return $this->convertValidationExceptionToResponse($e, $request);
}

return $this->prepareResponse($request, $e);
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, that's something new to me! I understand, but the problem is that I really need and return a json response if everything is okay, but if there are any errors, I'd like to handle the rendered html content in the error function of my ajax request. Would that be possible?
Thank you! That was exactly what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.