skip to Main Content

Every time I do an ajax request the Laravel always return the JSON response with so many whitespaces in front of the response text so the response always executed in error, not in the success section of ajax request, and I can’t show my error message too because it starts with white space so I can’t take the object notation, is there anything I can do to get rid of it?

Screenshot of response text :

enter image description here

My ajax request code :

$('.ajax-form').submit(function (e) {
  e.preventDefault();
  var form = $(this);

  $.ajax({
    dataType: "json",
    url: form.attr('action'),
    method: form.attr('method'),
    data: new FormData(this),
    contentType: false,
    cache: false,
    processData: false,
    success: function(result){
      console.log('success');
      alert(result.data.message);
      if (result.data.location) window.location.hash = result.data.location;
      location.reload(true);
    },
    error: function(err){
      console.log(err);
        if (err.status == 422) {
          let el = form.find('.error-block');
          el.find('.alert-danger').remove();
          console.log(err);
          $.each(err.responseJSON.errors, function (i, error) {
            let errorBlock = "<div class='alert alert-danger alert-dismissible'> "
                           + "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>"
                           + "<p><i class='icon fa fa-close'></i> " + error[0]+ "</p></div>";
            el.append(errorBlock);
            $('.modal').animate({ scrollTop: 0 }, 'fast');
          });
        }
      }
  });
});

My code in laravel :

public function insert(Request $request)
{
    $request->validate(['image' => 'required|image']);

    return response()->json(['data' => ['message' => 'Data is successfully updated!']]);
}

Actually this code work before I got this whitespace thing, I think this is the server-side who have the problem, but I didn’t change anything except I’ve do composer update before.

3

Answers


  1. Chosen as BEST ANSWER

    For now, I find my solution is to add ob_clean(); in Controller __construct method so I don't have to add it in every controller and request, but I hope there's a better solution than this.


  2. You can try set headers with “Accept” parameter to json into your ajax.

    $.ajax({
        ...,
        headers: {
            'Accept': 'application/json',
        },
        ...
    })
    
    Login or Signup to reply.
  3. Since I can’t add a comment yet, I will post a question here. can you please show us the dump the data in your controller before returning it to script?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search