Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to make a button that first runs js function and then function in .py

I am building a Django app and on one of my HTML sheets, I have a button that should first run a js function(ocr()) and then another function in the .py.

I've tried the first solution to this post. And now it runs the javascript function but it doesn't go on to the function in the .py.

UPDATE: I added the onsubmit event and the function returns true now. But it still doesn't work.

This is the js script:

<div>
        
        <script>
            var ocr = function(event){
                event.preventDefault();

                Tesseract.recognize(
                    document.getElementById('imgde').src,
                    'deu',
                    { logger: m => console.log(m) }
                ).then(({ data: {text}}) => {
                    console.log(text);
                    document.getElementById('txt_voc_de').innerHTML = ['<input type="hidden" name="txt_voc_de" id="txt_voc_de" value="',text, '"/>'].join('');
                })

                Tesseract.recognize(
                    document.getElementById('imgen').src,
                    'eng',
                    { logger: m => console.log(m) }
                ).then(({ data: {text}}) => {
                    console.log(text);
                    document.getElementById('txt_voc_en').innerHTML = ['<input type="hidden" name="txt_voc_en" id="txt_voc_en" value="',text, '"/>'].join('');
                })
                
                
   
                
            };

            var form = document.getElementById("imgForm");
            form.addEventListener("submit", ocr, true);
        </script>
        <input type="submit" onsubmit="ocr();" id="senden" class="inputfiles" />
        <button for="senden" class="button" id="weiter_btn" >WEITER</button>
        {% csrf_token %}
        </div>

UPDATE 2:

I am now trying to send a request to a URL in the JS function and have it be picked up by a view. But it only returns the previous html sheet.

This is the updated script:

<div>
        
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
            $(document).ready(function () {
                $("#imgForm").submit(function (event) {
                    event.preventDefault();
                    $.ajax({
                    type: "POST",
                    beforeSend: function() {
                        Tesseract.recognize(
                            document.getElementById('imgde').src,
                            'deu',
                            { logger: m => console.log(m) }
                        ).then(({ data: {text}}) => {
                            console.log(text);
                            document.getElementById('txt_voc_de').innerHTML = ['<input type="hidden" name="txt_voc_de" id="txt_voc_de" value="',text, '"/>'].join('');
                        })

                        Tesseract.recognize(
                            document.getElementById('imgen').src,
                            'eng',
                            { logger: m => console.log(m) }
                        ).then(({ data: {text}}) => {
                            console.log(text);
                            document.getElementById('txt_voc_en').innerHTML = ['<input type="hidden" name="txt_voc_en" id="txt_voc_en" value="',text, '"/>'].join('');
                        })
                    } ,
                    url: "/upload/",
                    success: function () {
                        $('#message').html("<h2>Contact Form Submitted!</h2>")
                    }
                    });
                    return false;
                });
                });
            
        </script>
       <input type="submit" id="senden" class="inputfiles"/>
       <button for="senden" class="button" id="weiter_btn" >WEITER</button>
        {% csrf_token %}
        </div>

The problem probably is that the beforesend function is in javascript right? But is there a way I can run that function in javascript before the ajax request?

And this is my function in views.py

def upload(request):
    if request.is_ajax():
        message = "Yes"
        txt_voc_en = request.POST.get("txt_voc_en")
        txt_voc_de = request.POST.get("txt_voc_de")
        print(txt_voc_de)
        print(txt_voc_en)

        vocsde = ocr_core(txt_voc_de)
        vocsen = ocr_core(txt_voc_en)
        
        messages.success(request, vocsde, extra_tags="de")
        messages.success(request, vocsen, extra_tags="en")
        context = {'vocsen': vocsen,
                    'vocsde': vocsde}
        return render(request, 'success.html', context)
     else:
        message = "Not ajax"
     return HttpResponse(message)



like image 280
anonimostilton Avatar asked Nov 06 '22 00:11

anonimostilton


1 Answers

As per your question, you first want to process some form data via JavaScript, embedding the results in hidden input types. Finally you want to send those hidden input's data to views.py for further process. In the updated script, you mixed javascript with AJAX. You can update you script as followed -

<script>
    var ocr = function(event) {
        event.preventDefault();

        Tesseract.recognize(
            document.getElementById('imgde').src,
            'deu', {
                logger: m => console.log(m)
            }
        ).then(({
            data: {
                text
            }
        }) => {
            console.log(text);
            Tesseract2(text);
        })
    };

function Tesseract2(text_de) {
    Tesseract.recognize(
        document.getElementById('imgen').src,
        'eng', {
            logger: m => console.log(m)
        }
    ).then(({
        data: {
            text
        }
    }) => {
        console.log(text);
        AjaxCall(text_de, text);
    })

}

function AjaxCall(text_de, text_en) {
    $.ajax({
        type: 'POST',
        url: "/upload/",
        data: {
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), // to avois csrf error
            txt_voc_en: text_en,
            txt_voc_de: text_de
        },
        success: function(json) {
            //Do whatever you want
        },
        error: function(xhr, errmsg, err) {
            console.log(xhr.status + ": " + xhr.responseText);
        }
    });
}

var form = document.getElementById("imgForm");
form.addEventListener("submit", ocr, true);
</script>

This code will first do preprocessing via javascript and then send it to views.py via AJAX with required parameters "txt_voc_en" and "txt_voc_de".

like image 129
Vishwas Patel Avatar answered Nov 12 '22 12:11

Vishwas Patel