JsonResponse and Ajax function.

58 views
Skip to first unread message

elcaiaimar

unread,
Feb 10, 2015, 8:33:58 AM2/10/15
to django...@googlegroups.com
Hello!

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":p.id} or {"status":"False"}
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?
Thank you very much!

template:

 <form method="post" id="frmEliminar">
      {% csrf_token %}
      <input type="hidden" id="modal_idProducto" name="product_id">
      <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);
});

Collin Anderson

unread,
Feb 19, 2015, 1:18:08 PM2/19/15
to django...@googlegroups.com
Hi,

Sorry for the late reply. Do you need to use JSON.parse(response).status?

Collin
Reply all
Reply to author
Forward
0 new messages