4

I am trying to send data from a javascript function that generates a random string upon the page loading to a Django view. I don't know how to structure the script tag to send the data after the page has loaded and the views.py to receive the data. I am new to javascript and don't quite know how to go about this. I appreciate any help provided.

index.html

<script>

    function makeid(length) {
        var result           = '';
        var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for ( var i = 0; i < length; i++ ) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    console.log(makeid(9));

</script>
1

2 Answers 2

4

You can use ajax to send data to Django view like following code.

javascript:

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    $.ajax({
        type: "GET",
        url: '/my_def_in_view',
        data: {
            "result": result,
        },
        dataType: "json",
        success: function (data) {
            // any process in data
            alert("successfull")
        },
        failure: function () {
            alert("failure");
        }
    });
}

urls.py:

urlpatterns = [
               url(r'^my_def_in_view$', views.my_def_in_view, name='my_def_in_view'),
               ...
]

views.py:

def my_def_in_view(request):
    result = request.GET.get('result', None)
    # Any process that you want
    data = {
            # Data that you want to send to javascript function
    }
    return JsonResponse(data)

If it was successfull it goes back to "success" part.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank You, I was able to solve the problem thanks to your answer
You're welcome. Great, so please accept this as the right answer to help other people who have the same problem.
0

you can do that in two ways:

  • Tradicional with ajax
  • Websockets: With django channels

If you want to send a bit of information, an ajax request is enough, you have to set and address and a view to receive the POST or GET ajax request.

I recommend to you use pure JS, not jquery

For example, this is a call to refresh a captcha image....

 /*Agregar boton refresh al lado del campo input*/
 let captcha_field =
     document.getElementById('captcha-field-registro_1').parentNode;
 let refresh_button=document.createElement('BUTTON');
 refresh_button.addEventListener('click',refresh_captcha)

 refresh_button.innerHTML = "Refrescar Captcha";                   // Insert text
 captcha_field.appendChild(refresh_button);

 let url_captcha= location.protocol + "//" +
                  window.location.hostname + ":" +
                  location.port + "/captcha/refresh/";

 let id_captcha_0="captcha-field-registro_0"
 function refresh_captcha(){
     let xhr = new XMLHttpRequest();
     xhr.open('GET', url_captcha, true);
     xhr.onload = function recv_captcha_load(event){
         console.log("event received", event,
                     "state",xhr.readyState);

         let data_txt = xhr.responseText;
         let data_json = JSON.parse(data_txt);
         console.log("Data json", data_json);

         if (xhr.readyState==4){
             if (xhr.status==200){
                 console.log("LOAD Se ha recibido esta información", event);
                 let captcha_img=document.getElementsByClassName('captcha')[0];
                 console.log("Catpcha img dom", captcha_img);
                 captcha_img.setAttribute('src', data_json['image_url'])
                 document.getElementById(id_captcha_0).value=data_json['key']
             }
             else{
                 console.log("Error al recibir")

             }
         }

     };

     var csrftoken = getCookie('csrftoken');
     xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
     xhr.setRequestHeader("X-CSRFToken", csrftoken);
     xhr.send();
 }

 function getCookie(name) {
     let cookieValue = null;
     if (document.cookie && document.cookie !== '') {
         var cookies = document.cookie.split(';');
         for (let i = 0; i < cookies.length; i++) {
             let cookie = cookies[i].trim();
             // 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;
 }


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.