PHP ajax response working but there is "undefined" text in the beginning of the div

So, i want to populate div with id "listberita" with html code from ajax response.

Here is the php code where contain div with "listberita" id

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Jabary - Website Budaya Jabar</title>
    <link href="" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="berita.css">


    <!-- Navbar  -->
    <?php include 'php/navbar.php'; ?>

    <div class="container my-5">
        <div class="kategoricaption mb-5">
            <div class="row">
                <div class="col">
                    <h1 class="text-center fw-bold judulkategori">Berita</h1>
                    <hr class="mx-auto" style="width:10%; background-color: #f49f16;">


        <div class="card-group vgr-cards" id="listberita">

    <!-- footer -->
    <?php include 'php/footer.php'; ?>

    <script src="" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    <script src="js/bootstrap.bundle.min.js "></script>
    <script src="berita.js"></script>



Here is my ajax js code

$(this).ready(function() {

    function getNews() {
            type: "GET",
            url: "_php/getBerita.php",
            dataType: "JSON",
            success: function(response) {
                var kode;
                $.each(response, function(i, obj) {
                    kode += '<div class="card kartu pb-3"><div class="card-img-body"><img class="card-img" src="img/Berita/' + obj.gambar_berita + '" alt="Card imagecap"></div><div class="card-body"><h4 class="card-title">' + obj.nama_berita + '</h4><p class="card-text">' + obj.keterangan_berita.substring(0, 250) + '....</p><a href="isiBerita.php?id=' + + '#disqus_thread" class="btn btn-success mt-5">Read More</a></div></div>'



Here is my php code where ajax request to (php_/getBerita.php)

  include '../koneksi.php';

    $result = $conn->query("SELECT * from tbl_berita");
    echo json_encode($data);


The code above is working, it’s return the data i want. But there is a problem.
Here is the problem

How to get rid the "undefined" thing on the beginning of div?

>Solution :

Try changing your var kode; to var kode = "";.

When you define the variable without initializing it, it will be undefined. And then your loop is appending text to an undefined variable. That’s probably why.

Leave a Reply