How to view error from AJAX, Javascript – Laravel

When you are calling an AJAX in Laravel, you will see a “500 – Internal Server Error” if there is an error in your PHP code. To see the actual error, kindly follow this article. We will teach you in this tutorial, how you can view error from your AJAX request.

Suppose I am calling an AJAX request in Laravel using core Javascript (no jQuery), then your code will be like this:

Javascript AJAX

var ajax = new XMLHttpRequest();
ajax.open("POST", document.getElementById("base-url").value + "/ajax-test", true);

ajax.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
    }

    if (this.status == 500) {
        console.log(this.responseText);
    }
};

var formData = new FormData();
formData.append("_token", document.querySelector("meta[name=_token]").content);
ajax.send(formData);

Line #1: I have created an AJAX object.

Line #2: I have opened the AJAX request with the POST method and the URL where the request will be sent. The third parameter (true, false) is the asynchronous boolean.

Note: All modern browsers recommend this value to be true.

Line #4: An event listener that will be called each time the status of request is changed.

#5: Check if the request is successful and the response has been received from server.

#6: Display the response from the server in browser console.

#9: Check if there is an internal server error. If yes, then display that error in line #10.

#14: New form data object is created that will send the data with an AJAX request.

#15: A CSRF (cross-side request forgery) token is appended in the form data object. We will create that meta tag later in this article.

Note: Every POST request in Laravel requires a CSRF token to be sent along with request.

Line #16: Sending the AJAX request along with form data object values.

You can create the hidden base URL and CSRF token tags as follows:

<input type="hidden" id="base-url" value="{{ url('/') }}">
<meta name="_token" content="{{ csrf_token() }}">

Now, whatever the error you are having on your server-side, in route, or in the controller, you will see that in your browser console window.

jQuery AJAX

If you are using jQuery to send an AJAX request and not seeing the actual error from your server-side, then change your jQuery AJAX function to the following:

$.ajax({
    url: document.getElementById("base-url").value + "/ajax-test",
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr) {
        console.log(xhr.responseText);
    }
});

Now, if you have an error in your AJAX request, you can view it in the “error” callback. Learn how to convert a simple POST request into an AJAX request following this tutorial.

[wpdm_package id=’938′]