2

I am developing a web application through Django and I want to get information from my javascript to a view of Django in order to access to the database.

I am using an ajax call as this post shows. I am calling the js in html by an onclick event :

sortedTracks.html

     ...
    <form action="{% url 'modelReco:sortVideo' video.id %}">
        <input type="submit" value="Validate" onclick="ajaxPost()" />
    </form>
    ...

clickDetection.js

//defined here
var tracksSelected = [];

//function that fill tracksSelected
function tagTrack(track_num){
  if(tracksSelected.includes(track_num)){
    var index = tracksSelected.indexOf(track_num);
    tracksSelected.splice(index, 1);
  }else{
      tracksSelected.push(track_num);
  }};

//ajax function
function ajaxPost(){
$.ajax({
    method: 'POST',
    url: '/modelReco/sortedTracks',
    data: {'tracksSelected': tracksSelected},
    success: function (data) {
         //this gets called when server returns an OK response
         alert("it worked! ");
    },
    error: function (data) {
         alert("it didnt work");
    }
});
};

So the information I want to transfer is tracksSelected and is an array of int like [21,150,80]

views.py

def sortedTracks(request):
if request.is_ajax():
    #do something
    print(request)
    request_data = request.POST
    print(request_data)

    return HttpResponse("OK")

The ajax post works well but the answer I get is only an empty Query Dict like this :
<QueryDict: {}> And if I print the request I get :

<WSGIRequest: GET '/modelReco/sortedTracks/?tracksSelected%5B%5D=25&tracksSelected%5B%5D=27&tracksSelected%5B%5D=29'>

I have also tried to change to request_data=request.GET but I get a weird result where data is now in tracksSelected[]

6
  • 1
    Why don't you try to access the key directly inside your view? E.g request.POST.get('tracksSelected') or request.GET.get('tracksSelected') Commented Jun 14, 2019 at 9:14
  • 3
    You aren't preventing the default form submit Commented Jun 14, 2019 at 9:14
  • 1
    Why bother having a form action if you want the data to be submitted via Ajax? Commented Jun 14, 2019 at 9:15
  • If I do ' request.POST.get('tracksSelected)'. It returns me None because the QueryDict is empty. The form action is in order to validate your choices you made on the webpage where you have to click on different things. I am new so maybe I didn't catch something important in what you said. Commented Jun 14, 2019 at 9:19
  • Where do you define tracksSelected in that JS? Commented Jun 14, 2019 at 9:25

2 Answers 2

0

I've tried to know why if I was doing request_data=request.GET, I get the data like this tracksSelected[] and get only the last element of it.

And I found a way to avoid to have an array in my data (tracksSelected) on this link This enables me to have :

in views.py

def sortedTracks(request):
if request.is_ajax():
    #do something
    print(request)
    request_data = request.GET.getlist("tracksSelected")[0].split(",")
    print(request_data)

and in clickDetection.js

function ajaxPost(){
tracksSelected = tracksSelected.join();
$.ajax({
    method: 'POST',
    url: '/modelReco/sortedTracks',
    data: {'tracksSelected': tracksSelected},
    success: function (data) {
         //this gets called when server returns an OK response
         alert("it worked! ");
    },
    error: function (data) {
         alert("it didnt work");
    }
});
};

This little trick works and I am able to get the array data like this, print(request_data) returns my array such as [21,25,27]

Thank you for helping me !

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

Comments

0

According to me to access the data which is sent in the ajax request can be directly accessed . For Example:

def sortedTracks(request):
    if request.method == 'POST':
        usersV = request.POST.get('tracksSelected')[0]

            for users in usersV:
                print users
        return HttpResponse("Success")
    else:
        return HttpResponse("Error")

The correct syntax is data: {tracksSelected: tracksSelected},

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.