user17236681
user17236681

Reputation:

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data on jQuery

This seems to be a common "problem" but I could not find a solution somewhere else, so I'm asking here.

I get this with ajax from a flask app, which seems to be valid JSON (at least to me).

error

Any hints at what's wrong?

$('.categoryCheckbox').click(function(id) {
  $('.courseFilters').empty();
  $.ajax({
    type: 'GET',
    url: 'getCategoryCourse/' + id,
    success: function(response) {
      var respons = jQuery.parseJSON(response);
      console.log(respons);
      if (respons.length == 0) {
        $('.courseFilters').append('هیچ رکوردی ثبت نشده است');
      } else {
        respons.forEach(element => [
          $('.courseFilters').append(`<div class="row">
  <div class="col-lg-4 mb-3">
    <div class="card">
      <img src="${asset('storage/'.element.image)}" class="card-img-top" alt="${element.title}">
      <div class="card-body">
        <h5 class="card-title">${element.title}</h5>
      </div>
      <div class="card-footer p-0">
        <div class="d-flex justify-content-between">
          <div class="d-flex align-items-center ps-3">${element.body}</div>
          <div>
            <a href="${element.path()}">
              <span class="bg-info d-inline-block p-2"><i class="fas fa-cart-plus fa-2x"></i></span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>`)
        ]);
      }
    }
  })
})

Upvotes: 0

Views: 510

Answers (1)

Serge
Serge

Reputation: 43860

there is a bug in the code

var respons = jQuery.parseJSON(response);

Remove this line, you should not parse the result, it returns javascript object already

and for the future, it is better to use this syntax, when you really need to parse something

JSON.parse(....)

Upvotes: 3

Related Questions