AJAX function is not getting the id

Viewed 244

I am trying to fix this problem for about 3 days and can not do it. I need to take the id from which is auto incremented in the Django. Can you guys help me please.

function add_product(){
  event.preventDefault();
  var name = $("#name").val();
  var price = $("#price").val();
  var description = $("#description").val();
  var dataString = [name, description, price];
  var n = dataString.length;
  $.ajax({
    type: "POST",
    url: "add/",
    data: {
      csrfmiddlewaretoken: '{{ csrf_token }}',
      name: $('#name').val(),
      email: $('#price').val(),
      description: $('#description').val(),
    },
    dataType: "json",
    success: function(){
      var button = $('<button class="reo"  onclick="delete_product('+ I need to take the id from the database+')" id="my" value="">Delete</button>');
      var row = $('<tr>');
      for(var i = 0; i < n; i++) {
        row.append($('<td>').html(dataString[i]));
      }

      $('#tableForm').append(row);
      $('#tableForm').append(button);
    }
  });
};
1 Answers

Pass the returned data to your success function as below,

success:function(data) {
...
  var button = $('<button class="reo"  onclick="delete_product('+ data +')" id="my" value="">Delete</button>');
...
}

Your view should be returning the new created id in the HttpResponse. For example (assuming python/django backend),

Return HttpResponse(new_record.id, status=200)

Hope this helps!

Related