mardi 27 octobre 2020

Django/Heroku AJAX Request Doesn't Seem To Execute

I am needing to save the contents of a javascript variable in the main page of my site (index.html), to the database that my heroku/django app is connected to. I found a related post here but my AJAX request to send a variable from JavaScript to then access in python is not running.

Javascript/HTML and AJAX in index.html:


    <button type="button" id="send-my-url-to-django-button">Send URL to Django View</button>
    
    <script type="text/javascript">
        $(document).ready(function() {
            var url = data.result.docs[i].source.enriched.url.url;
            alert("ok");
            $("#send-my-url-to-django-button").click(function() {
                $.ajax({
                    url: "/process_url_from_client",
                    type: "POST",
                    dataType: "json",
                    data: {
                        url: url,
                        csrfmiddlewaretoken: ''
                        },
                    success : function(json) {
                        alert("Successfully sent the URL to Django");
                    },
                    error : function(xhr,errmsg,err) {
                        alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
                    }
                  return false;
                });
            });
        });
    </script>

relevant lines from urls.py

url(r'^process_url_from_client/$', hello.views.process_url_from_client, name='process_url_from_client'),

relevant lines from views.py


    def process_url_from_client(request):
        url = request.POST.get('url')
        save = SaveFile(data=str(url));
        save.save();

This is supposed to send the URL from index.html to then be accessed in views.py and saved to the database. However clicking the button does not seem to execute the AJAX script at all. I don't get a success or error message.

Any ideas why this isn't working? Any help would be appreciated.

NOTE: There is no issue saving to the database, the issue is posting the data to then be accessed in views.py.




Aucun commentaire:

Enregistrer un commentaire