jQuery Ajax generating image error

Asked

Viewed 124 times

0

I have the following code:

<table class="table" id="historico">
  <thead>
    <tr>
      <th>Hora</th>
      <th>Música</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

And the script:

setInterval(function() {

$.ajax({
  url: 'http://cors.io/?http://somdomato.com:8000/played',
  type:'GET',
  success: function(retorno){
    var html = "";
    $("<table>").html(retorno).find('tr').slice(3).each(function () {
      var arrayColuna = [];
      $(this).find('td').each(function () {
        arrayColuna.push("<td>" + $(this).text() + "</td>");
      });
      html += "<tr>" + arrayColuna.slice(0,2) + "</tr>";
    });
    $("#historico > tbody").html(html);
  }
});

}, 10000);

Only this generates errors in the console, for example:

http://localhost/user/Lucas/test/images/history.png Failed to load Resource: the server responded with a status of 404 (Not Found)

How to prevent this?

  • are you sure your url ta is correct? It doesn’t make much sense to have an http inside another http, sometimes this is causing the error

  • Yes, Cors.io is because I can’t parse from my local machine, only on the server, when I’m in production I take that Cors.io, the script works normal, but the error is displayed on the console. Got it?

  • @leofontes looks at the code working: http://i.imgur.com/Ophr7ln.png

1 answer

1


Gave this error because your image was not found, check if you are putting the right way.

Something you can do is check if the image exists and if it does not exist you display an image message not available, example:

$('img[data-src]').each(function() {
  var self = $(this);

  self.attr('alt', "Carregando...");
  
  var src = self.attr('data-src');

  var img = new Image();

  img.onload = function() {
    self.attr('src', src);
    self.attr('alt', "");
  }
  img.onerror = function() {
    self.attr('alt', "Imagem não encontrada");
  }
  img.src = src;

});
img {
  width: 200px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img data-src="path/invalido/img.png" />

<img data-src="http://www.generalpepper.com.br/wp-content/uploads/2013/08/bacon1.jpg" />

The attribute data-src is just to leave the src tag without being loaded by default and having a syntax in HTML5 default.

In Jquery I am creating a Image that represents the tag <img />, in it I put a callback in the onload for when load the image put the value of the data-src in the src of <img /> to load the image normally and a callback on onerror for when the image is not found put in the alt of <img /> a message from "Not found".

It is necessary to set a minimum height and width for the image if not the message of alt do not appear.

  • But I don’t want to upload the image, only the table that matters.

Browser other questions tagged

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