Riansyah Jalil
Riansyah Jalil

Reputation: 33

how to solved json.parse when data is empty in ajax

I following this code to show my data in table, but this code error when data empty, "error JSON.parse: unexpected character at line 1". please.. help me how can I solved this problem, and I want to make alert when json data is empty

$('#pilih').click(function(){
        const unit = document.getElementById('unit').value;
        const nosam = document.getElementById('nosam').value;
$.ajax({
            url: 'get/penjualan_data.php',
            data: {'unit': unit, 'nosam': nosam},
            cache: false,
        }).then(function(data){
            const json = data;
            obj = JSON.parse(json);
            
    var $table = $('#tampilkan tbody');
    for (var i = 0; i < obj.length; i++) {
    const a = i+1;
            var $row = 
                $("<tr>" +
        "<td>"+ a +"</td>" +
        "<td><input type='checkbox'></td>" +
                  "<td class='id'>"+ obj[i].nosam +"/"+ obj[i].gol +"</td>" +
        "<td>"+ obj[i].unit +"</td>" +
                  "<td class='nama'>"+ obj[i].nama +"</td>" +
        "<td>"+ obj[i].alamat +"</td>" +
                  "<td>"+ blnIndo(parseInt(obj[i].bulan)) +" "+ obj[i].tahun +"</td>" +
        "<td>"+  +"</td>" +
                  "<td style='text-align: right;' class='rp'>"+ titikAngka(obj[i].rupiah) +"</td>" +
                  "</tr>");
      
             $row.data(obj.nosam);
             $row.data(obj.nama);
             $row.data(obj.rupiah);
             $table.append($row);
   });
  });

Upvotes: 1

Views: 616

Answers (3)

Kinglish
Kinglish

Reputation: 23654

Make sure your php script penjualan_data.php outputs {} if there is no data to display. Your error is that you're not receiving a proper JSON object in your response.

So even if $data=""; Still finish with echo json_encode($data);

Upvotes: 0

Charlie
Charlie

Reputation: 23798

As the first attempt, you can simply check your json data is empty.

if (json)
  obj = JSON.parse(json);

If your code can still get inputs with invalid json, use try-catch.

try {
 obj = JSON.parse(json);
}
catch(e) {
   console.log(e)
}

Upvotes: 1

chri3g91
chri3g91

Reputation: 1410

Display an alert, or empty table or an alternative layout, if no data is returned by the request.

 if(!data) { alert('sorry, no data was retrieved'); return; }

Upvotes: 0

Related Questions