micky micky - 2 months ago 17
jQuery Question

Getting data-id in jQuery

I have

$display
variable passed:

echo json_encode(array('status' => TRUE, 'display'=>$display)); die;


jQuery and AJAX:

$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data)
{
var res = $.parseJSON(data);
if(res.status == true)
{ var results='';
if(res.display[i].type=='1')
{
var b="Business";
}
if(res.display[i].type=='2')
{
var b="Economy";
}
for(var i=0; i<res.display.length; i++)
{
results +='<tr><td>'+(i+1)+'</td><td>'+res.display[i].name+'</td><td>'+b+'</td><td>'+res.display[i].seat+'</td><td>'+res.display[i].date_booked+'</td><td></td><td><a href="" class="remove" data-id='+res.display[i].id+'>Cancel ticket</a></td></tr>'
}
}


res.display[i].date_booked
,
res.display[i].seat
,
res.display[i].name
are fine but what is wrong with
data-id='+res.display[i].id+'
?

Answer

You forgot the quotes:

// Note the `a` tag's `data-id` is changed from:
//   data-id='+res.display[i].id+'>
// to
//   data-id="'+res.display[i].id+'">
results += '<tr>' + 
             '<td>'+(i+1)+'</td>' +
             '<td>'+res.display[i].name+'</td>' +
             '<td>'+b+'</td>' +
             '<td>'+res.display[i].seat+'</td>' +
             '<td>'+res.display[i].date_booked+'</td>' +
             '<td></td>' +
             '<td><a href="" class="remove" data-id="'+res.display[i].id+'">Cancel ticket</a></td>' +
           '</tr>';

Can I suggest you format your code as follows? So it's more readable:

$.ajax({
  type: frm.attr('method'),
  url: frm.attr('action'),
  data: frm.serialize(),
  success: function (data) {
    var res = $.parseJSON(data);

    if (!res.status) return;

    var results = '';
    for (var i = 0;  i < res.display.length;  i++) {    
      results += '<tr>' + 
             '<td>'+(i+1)+'</td>' +
             '<td>'+res.display[i].name+'</td>' +
             '<td>'+b+'</td>' +
             '<td>'+res.display[i].seat+'</td>' +
             '<td>'+res.display[i].date_booked+'</td>' +
             '<td></td>' +
             '<td><a href="" class="remove" data-id="'+res.display[i].id+'">Cancel ticket</a></td>' +
           '</tr>';
    }
  }
});