I've written a code to delete db registers and I want to call an ajax function when the delete is done.
At the moment, when I click my delete button I only receive a message: {"status":"True","product_id":
and this should be sent to the ajax function and I shoud have an alert saying to me: product has been removed.
I don't know why, probably there is something wrong in the relation of my JsonResponse and ajax function.
I put my code below. Does anybody know how can I fix this?
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">Cerrar</
button>
<button type="submit" class="btn btn-danger">Eliminar</button>
</form>
views.py:if request.method=="POST":
if "product_id" in request.POST:
try:
id_producto = request.POST['product_id']
p = Pozo.objects.get(pk=id_producto)
mensaje = {"status":"True","product_id":
p.id}
p.delete() # Elinamos objeto de la base de datos
return JsonResponse(mensaje)
except:
mensaje = {"status":"False"}
return JsonResponse(mensaje)
Ajax.js:
// Autor: @jqcaper
// Configuraciones Generales
var nombre_tabla = "#tabla_productos"; // id
var nombre_boton_eliminar = ".delete"; // Clase
var nombre_formulario_modal = "#frmEliminar"; //id
var nombre_ventana_modal = "#myModal"; // id
// Fin de configuraciones
$(document).on('ready',function(){
$(nombre_boton_eliminar).on('click',function(e){
e.preventDefault();
var Pid = $(this).attr('id');
var name = $(this).data('name');
$('#modal_idProducto').val(Pid);
$('#modal_name').text(name);
});
var options = {
success:function(response)
{
if(response.status=="True"){
alert("Eliminado!");
var idProd = response.product_id;
var elementos= $(nombre_tabla+' >tbody >tr').length;
if(elementos==1){
location.reload();
}else{
$('#tr'+idProd).remove();
$(nombre_ventana_modal).modal('hide');
}
}else{
alert("Hubo un error al eliminar!");
$(nombre_ventana_modal).modal('hide');
};
}
};
$(nombre_formulario_modal).ajaxForm(options);
});