Alex Pinto
Alex Pinto

Reputation: 31

Django: Ajax not receiving data from server response

I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page.

Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file.

However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data.

Views.py

i=0
uploaded_file = None


def home(request):

    if (request.method == 'POST'):
        file_form = UploadFileForm(request.POST, request.FILES)
        if file_form.is_valid():
            global uploaded_file
            uploaded_file = request.FILES['file']
            print(uploaded_file)
    else:
        file_form = UploadFileForm()

    return render(request, 'personal/home.html', {'form': file_form})



def handle(request):

    # TODO make ajax wait for a response from 'home'
    # so I don't have to wait for 1 second  
    time.sleep(1)
    data = {}
    data['Name'] = fileName(uploaded_file)
    if(request.is_ajax()):
        print(data)        # prints succesfully
    return HttpResponse(json.dumps(data), 
content_type="application/json")

home.html

        <script type = "text/javascript" language = "javascript">

        function post_tables(data) {
            alert(data)
        }


         $(document).ready(function(post_tables) {
            $("#upload").click(function(event){
               $.ajax( {
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  type: "get",
                  url:'/handler',
                  success: function(data) {
                     console.log("over here")
                     post_tables(data)
                  },
                  error: function(data) {
                      console.log("down here")
                      post_tables("error being thrown")
                  }
               });
            });
         });
        </script>

urls.py

urlpatterns = [
    path(r'', views.home, name='home'),
    path(r'handler', views.handle, name='handle'),
]

Upvotes: 3

Views: 1634

Answers (1)

rmaleki
rmaleki

Reputation: 752

I explained the whole process ajax django to you. Perhaps your problem will be solved. good luck.

views.py

def handle(request):
    if request.method == 'POST':
        data = request.POST
        field_example = data.get('field_example')

        return JsonResponse(data)
    else:
        data = request.GET
        field_example = data.get('field_example')
        return JsonResponse(data)

home.html

<form id="upload">
   {% csrf_token %}
   <input type="text" name=field_example>
   .
   .
   .
</form>

urls.py

urlpatterns = [
    path(r'', views.home, name='home'),
    path(r'handler/', views.handle, name='handle'),
]

js code in home.html:

$("#upload").submit(function (e) {
    e.preventDefault();
    var formData = new FormData(this);

    $.ajax({
        url: "{% url 'handle' %}",

        type: 'GET',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log("over here")
            post_tables(data)
        },
        error: function (data) {
            console.log("down here")
            post_tables("error being thrown")
        }
    });
});

Upvotes: 1

Related Questions