Popular list-group bootstrap with ajax

Asked

Viewed 228 times

1

Hello to you all.

I’m trying to popular a bootstrap list-group with ajax but I’m not getting it. I’ve researched several places about it and I couldn’t solve it.

The php code is ok and the json that returns from php is also ok.

Follow the html code

<!DOCTYPE html>
<html>
<header>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<script type="text/javascript">
$(document).ready(function(){
$('#lista').empty();
$.ajax({
    type:'GET',
    url: 'artigos.php',
    dataType: 'json',
    success: function(dados){
        for(var i=0;dados.length>i;i++){
            $('#lista').append('<a href=\"artigos/'+dados[i].link+'?id='+dados[i].id'\" class=\"list-group-item\">'+dados[i].titulo+'</a>');
        }
    }
});
});
</script>
</header>
<body>
<div class="page-header text-center">
<h1>Artigos <br /><small>Selecione um item para ler o artigo</small></h1>
</div>
<div class="list-group" id="lista">

</div>
<script src="js/jquery-3.2.1.min.js"></script>
</body>
</html>

2 answers

2


You are escaping needlessly quotes and generating invalid HTML.

Instead of \" you should only have " once you start the strings with single quote '.

Then changes

$('#lista').append('<a href=\"artigos/'+dados[i].link+'?id='+dados[i].id'\" class=\"list-group-item\">'+dados[i].titulo+'</a>');

(and correcting the + missing in +dados[i].id'), for:

$('#lista').append('<a href="artigos/' + dados[i].link + '?id=' + dados[i].id + '" class="list-group-item">' + dados[i].titulo + '</a>');
  • 1

    It worked by taking a look here was my fault, as apart from the problem you pointed out, the file was with different name in js folder. Thanks for the help!

2

In addition to the problems cited in the @Sergio reply, there is another error in your code that is the cause of the problem: you are loading jQuery at the end of the document, after the code.

Load the jQuery library preferably on <head> of the document:

<head>
<script src="js/jquery-3.2.1.min.js"></script>
</head>
  • Thanks, but even putting in the head hasn’t worked yet.

  • It worked by taking a look here it was my fault, because in addition to having placed the jquery call at the bottom of the page, the file was with different name in the js folder. Thanks for the help!

Browser other questions tagged

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