0

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!

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

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.