0

I have no problem with the request and response process, Until I try to parse/process the json data returned from laravel when the error occurs.

I want to display a messsage error when the uploaded file is larger than the system accepts. My action is something like this:

...
if($_FILES['file1']['size'] > 0)
  {
    http_response_code(413);
    return Response()->json(["errorMsg" => "Your file is too large!"], 413);


  }
....

Client code:

  $.ajax({
                type: "POST",
                url: "/anuncio/realizar_upload_foto",
                 contentType: false,
                cache: false,
                dataType: "JSON",
               processData: false

...

...
    error: function (xh, jso) 

            {


                  alert(jso.errorMsg); //undefined here



                }

            });
2
  • 1
    you should send message by success method in , because error method run when Ajax requests complete with an error Commented Jun 25, 2017 at 18:26
  • @Mohammadb but actually, the Ajax request in the question do complete with an error (413) Commented Jun 26, 2017 at 1:22

2 Answers 2

1

In your way, you should find your data in xh.responseJSON.errorMsg

But you should follow REST Api practice.

First of all you should return json code 200 and pass your status message like.

return response()->json([
    "status" => "success",
    "data" => [....yourdata]
], 200);

in error case

return response()->json([
    "status" => "error",
    "msg" => "Your file is too large!"
], 4**);
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I think "alway return 200" is not a RESTful API practice. If error happens, the most appropriate status code should be returned.
@shaochuancs sry, i made mistake. of course it should return errorcode
0

According to the jQuery.ajax() document, the error callback accepts 3 parameters:

error

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

The second parameter (jso in your code) is just a String indicating status ("error" for example). It does not contain any HTTP response body data.

To get errorMsg in the error callback, you need to use the first parameter (jqXHR). Example code would be:

error: function(jqXHR, status, error) {
  var errorObj = jqXHR.responseJSON; // This only works when dataType is defined as "JSON", or the "Content-Type" of HTTP response is "application/json". Otherwise, use the below general code.
  //var errorObj = JSON.parse(jqXHR.responseText);

  alert(errorObj.errorMsg);
}

Comments

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.