Django, Do not send data to the bd with ajax

1

By pressing the submit button of the form. go to the error function of the script.js file, when looking at console " POST / HTTP / 1.1" 200 28518 , the database is postgres. is not saving the data, I have reviewed several pages online but I can not find the solution, I just want to send the data without reloading the page any ideas?

script.js

var clContactForm = function() {

        /* local validation */
        $('#contactForm').validate({

            /* submit via ajax */
            submitHandler: function(form) {

                var sLoader = $('.submit-loader');

                $.ajax({

                    type: "POST",
                    url: $(this).attr(''),
                    data: $(form).serialize(),
                    beforeSend: function() { 

                        sLoader.slideDown("slow");

                    },
                    success: function(msg) {

                        // Message was sent
                        if (msg == 'OK') {
                            sLoader.slideUp("slow"); 
                            $('.message-warning').fadeOut();
                            $('#contactForm').fadeOut();
                            $('.message-success').fadeIn();
                        }
                        // There was an error
                        else {
                            sLoader.slideUp("slow"); 
                            $('.message-warning').html(msg);
                            $('.message-warning').slideDown("slow");
                        }

                    },
                    error: function() {
                        sLoader.slideUp("slow"); 
                        $('.message-warning').html("Something went wrong. Please try again.");
                        $('.message-warning').slideDown("slow");

                    }

                });
            }

        });
    };

form.html

 <form name="contactForm" id="contactForm" method="post" >

                    {% csrf_token %}


                    <fieldset>

                       {{form.nombre}}
                       {{form.email}}
                       {{form.telefono}}
                       {{form.mensaje}}


                        <div class="form-field">
                            <button class="full-width btn--primary">Submit</button>
                            <div class="submit-loader">
                                <div class="text-loader">Sending...</div>
                                <div class="s-loader">
                                    <div class="bounce1"></div>
                                    <div class="bounce2"></div>
                                    <div class="bounce3"></div>
                                </div>
                            </div>
                        </div>

views.py

def contacto(request):
    contactos = Contacto.objects.all()
    if request.method == 'POST':
        formulario = ContactoForm(data=request.POST)
        if formulario.is_valid():
            formulario.save()
    else:
        formulario = ContactoForm()
    return render(request, 'formulario.html', {'contactos': contactos, 'form': formulario})
    
asked by Developer 06.11.2018 в 14:51
source

2 answers

0

Greetings I'll give you an example:

Assuming I have the following html form:

<form name="contactForm" id="contactForm">
 {% csrf_token %}
{{form.nombre}}
{{form.email}}
{{form.telefono}}
{{form.mensaje}}

<button class="full-width btn--primary" onclick="grabarDatos();">Grabar Datos</button>
</form>

If you look at the button I added the onclick event that invokes a function called RecordData this function is JavaScript:

    <script>
    function getCookie(name) {

      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      //RETORNANDO EL TOKEN
      return cookieValue;

  }//end function getCookie

    function grabarDatos(){
     var nombre = $("#id_nombre").val();
     if(nombre =="" || nombre == null){
     alert("ingrese un nombre");
     return false;
     }
     var email = $("#id_email").val();
     if(email =="" || email == null){
     alert("ingrese un correo");
     return false;
     }
     var telefono = $("#id_telefono").val();
     if(telefono =="" || telefono == null){
     alert("ingrese un telefono");
     return false;
     }
     var mensaje = $("#id_mensaje").val();
     if(mensaje =="" || mensaje == null){
     alert("ingrese un mensaje");
     return false;
     }

    //envio por ajax
    //token
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        type: "POST",
        url: "crear_contacto",
        data:{
        csrfmiddlewaretoken : csrftoken, 
        nombre:nombre,
        email:email,
        telefono:telefono,
        mensaje:mensaje,
        },
        dataType: "json",
        success: function(data) {
        codigo = data.resultado;
        if(codigo=='ok_insert'){
          alert("Datos Grabados con exito !!");
        }
        },
        error: function( jqXHR, textStatus, errorThrown ) {

        if (jqXHR.status === 0) {

            alert('Error al intentar Conectarse: Verifique su conexion a Internet.');

        } else if (jqXHR.status == 404) {

            alert('La Pagina solicitada no fue encontrada [404]');

        } else if (jqXHR.status == 500) {

            alert('Erro Interno [500]');

        } else if (textStatus === 'parsererror') {

            alert('Error en el retorno de Datos. [parseJson]');

        } else if (textStatus === 'timeout') {

            alert('Tiempo de Espera agotado');

        } else if (textStatus === 'abort') {
            alert('Solicitud Abortada. [Ajax Request]');

        } else {
            alert('Error desconocido: ' + jqXHR.responseText);
        }//end if 

        }//end error
    }); 
    }//end function grabarDatos
    </script>

As you set the data in variables such as name, email, phone, message to be sent later by ajax. now your views.py :

def CrearContacto(request):

    if request.method == 'POST':
      nombre = request.POST.get('nombre')
      email = request.POST.get('email')
      telefono = request.POST.get('telefono')
      mensaje = request.POST.get('mensaje')
      #insertando la data
      contacto = Contacto(
      nombre = nombre,
      email = email,
      telefono = telefono,
      mensaje = mensaje,
      )
      contacto.save()
      data ={
    'resultado':'ok_insert'
      }
      return HttpResponse(json.dumps(data), content_type="application/json")

now something very important for ajax is the url that is where you will send the data, which is defined in your urls.py:

from myapp.views import CrearContacto
urlpatterns = [
  ......
  ......
  url(r'^crear_contacto', CrearContacto, name='crear_contacto')
]

Ready with this already would be basically all your ajax, something very important that you must include for ajax is the token otherwise it will generate error.

Token Django Ajax

I hope you serve and luck !!

    
answered by 06.11.2018 / 23:25
source
1

Integrate it into some static folder of your project Refer to the script in your html template as follows: Done! Now you can make your requests without having to worry about the token:)

  /**
     * Este script de javascript permite trabajar transparentemente solicitudes que requieren 
     * protección del token CSRF por medio de AJAX JQUERY.
     * Esto te permitirá hacer solcitudes a web Services de Django por medio de AJAX Jquery.
     * Para utilizarlo basta con integrar el archivo DjangoAjax.js en tu directorio de JS  y hacer referencia a él en tus templates 
     * que requieren del uso de AJAX por POST o algún otro que requiera el token CSRF.
     * Este script está basado en la documentación oficial de Django https://docs.djangoproject.com
     */

    $(function(){
        //Obtenemos la información de csfrtoken que se almacena por cookies en el cliente
        var csrftoken = getCookie('csrftoken');

        //Agregamos en la configuración de la funcion $.ajax de Jquery lo siguiente:
        $.ajaxSetup({
                        beforeSend: function(xhr, settings) {
                            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                                // Send the token to same-origin, relative URLs only.
                                // Send the token only if the method warrants CSRF protection
                                // Using the CSRFToken value acquired earlier
                                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                            }
                        }
        });

    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }

    // usando jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }


        function csrfSafeMethod(method) {
            // estos métodos no requieren CSRF
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
    });

The example of a query would be

$.ajax({
    url: 'mi_url',
    type: "POST",
    data: {'variable': value},
    success: function (response) {
       //lo que haces si es exitoso
    }

});

And your file so that it is only for ajax queries for an api-rest

def ajax_test(request):
    if request.is_ajax():
        message = "This is ajax"
    else:
        message = "Not ajax"
    return HttpResponse(message)
    
answered by 07.11.2018 в 01:55