Home > OS >  Pass Array to backend using Ajax (Django)
Pass Array to backend using Ajax (Django)

Time:10-08

I am learning AJAX and I am having trouble passing an array to the backend. I can pass a simple variable and my code works great, but when I pass an array I am not able to pass the data successfully.

My code is below (this works):

    function add_var() {
    var aa = 5;

    $.ajax({
        url : "add_variable/",
        type : "POST", 

        data : { num1 : aa},
        
        success : function(json) {
            $('#num3').val(json); 
        },

        error : function() {
            console.log("fail");
        }
    });
    };

This works just fine and I can pass 5 to the backend. However when I change aa to an array, the function no longer works and returns a 'None' on the Views backend.

    function add_var() {
    var aa = [5,10,15];

    $.ajax({
        url : "add_variable/",
        type : "POST",

        data : { num1 : aa},
        
        success : function(json) {
            $('#num3').val(json); 
        },

        error : function() {
            console.log("fail");
        }
    });
    };

Could someone point me in the right direction here? Any help is appreciated!

CodePudding user response:

You can do it that way for any string or numbers, but as soon as you need to pass back an object (such as array) you need to "stringify"

data : {num1 : JSON.stringify(aa)}

Then, you would have to "Parse" or "Deserialize" the string which converts it back to an object.

I believe in django, it would look something like this:

import json
nums = json.loads(num1)
  • Related