2

I'm trying to use "Bootstrap File-input" plugin for JQuery in order to upload files using AJAX. The plugin expects error messages being recieved in a JSON key called "error" as following:

{error: 'You are not allowed to upload such a file.'}

So I wrote my own code for exception handling in the "Render" method of "Handler" class:

public function render($request, Exception $exception){

    $err_code = $this->getExceptionHTTPStatusCode($exception);

    $data = [
        "error" => "Internal Server error.",
        "exception" => $exception->getMessage()
    ];

    if ($exception instanceof ValidationException){
        $data['error'] = "Wrong input data";
        $data['error_list'] = $exception->getResponse()-> getOriginalContent();
        $err_code = 422;
    }

    if ($request->expectsJson()) {

        return response()->json(
            $data, 
            $err_code
        );

    }

    return parent::render($request, $exception);
}

But instead of recieving the data as expected, it puts array's content in the "responseText" key value (and also it's escaped as a string):

{"readyState":4,"responseText":"{\"error\":\"Wrong input data\",\"exception\":\"The given data failed to pass validation.\",\"error_list\":{\"logotipo\":[\"Logotipo field is mandatory\"]}}","responseJSON":{"error":"Wrong input data","exception":"The given data failed to pass validation.","error_list":{"logotipo":["Logotipo field is mandatory."]}},"status":422,"statusText":"Unprocessable Entity"}  

I'm wondering if I can put another key and value in the same level as "responseText", just as "JSONResponse" (I don't know how it works, but it appears to be appended by the Laravel's Validator) but as a JSON Object, instead of a String. I know that I can parse the string with JQuery, but "Bootstrap File Input" plugin expects it as a JSON and I can't modify its code.

I also tried to use Vue.js resources plugin, but it appears that it reads the response in a different way, so that my "responseText" object is called "body" and "bodyText", which have the same content. I don't know why I'm getting duplicated responses, one as a escaped string and one as a JSON.

Thank you.

1 Answers1

2

If I am not wrong you are trying to submit your form with file input using ajax. For this, I can share these following links for you and these guys have already solved the same problem.

Laravel 5 Ajax File/Image Upload

AJAX file upload in laravel

Laravel 5 Ajax File/Image Upload

May be this can provide you some help.

Harish
  • 462
  • 6
  • 13