Nothing happens in Success, even if Json returns

Asked

Viewed 39 times

1

The return is giving 200 Json, but nothing is excommunicated in Success.

$(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  $('#form_result').html('');
  $.ajax({
   url:"/dashboard/admin/titulos/"+id+"/edit",
   dataType:"json",
   success:function(html){
    alert("não roda nada dentro do SUCCESS")
   }
  })
 });

1 answer

2


There are two possibilities.

The first possibility is your request to return an HTML, because analyzing this line $('#form_result').html(''); implies that you have deleted the HTML code from form_result and is ready to put the result of your request into place. In this scenario the value for the return of dataType:"json" would be causing the problem, because if a poorly formed JSON is returned even the operation having resulted in a Status HTTP 200 the callback success() will not be invoked and in this case an HTML is returned.

So to correct is just to adjust the dataType the request:

$(document).on('click', '.edit', function(){
    var id = $(this).attr('id');
    $('#form_result').html('');
    $.ajax({
       url:"/dashboard/admin/titulos/"+id+"/edit",
       dataType:"html",  //<-- Aqui onde era JSON virou HTML
       success:function(html){
          $('#form_result').html(html);
       }
    })
});

success() is only called if there is no server error and there is no error with the returned data structure, implying that a poorly formed html coming from the server would also be a problem if the specified format is changed to html.


The second possibility, less plausible, is that actually the return can be a JSON only that it is poorly formed preventing the execution of success(). So when you are unsure of the consistency of the returned data, or if there is awareness of the possibility of failure in the process of making the data or if there is a need to work the data in the reception use .done() that is invoked when the server return is OK independent of the returned data.

$(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  $('#form_result').html('');
  $.ajax({
     url:"/dashboard/admin/titulos/"+id+"/edit",
     dataType:"json" 
  })
  .done(function(html){
     alert("Agora funciona");         
  });
});
  • 1

    Man, thank you so much. Your answer was a class.

  • Actually the json was poorly formed, I made the return correction in the backend and it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.