[Fixed]-Ajax function doesn't execute when any of the input fields are not supplied in django

1πŸ‘

It sounds like those values are optional?

If so, perhaps you can check to see if those values exist, and if not, just submit an empty string:

data: {
                'pname_Aj': ( $('#pname').val() || ""),
                'psection_Aj': ( $('#psection').val() || ""),
                'rinput_Aj' : (JSON.stringify(fun()) || ""),
                'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val()
            },

So if the user has entered values in those sections (and fun() returns something that can be stringified, those variables get submitted. Otherwise, an empty string gets submitted.

πŸ‘€TerryCB

0πŸ‘

If the parameters need to be absent when no value

function saveprof() {
    $('.spinner').show();
    $.ajax({
        type: "POST",
        url: "saveprof",
        enctype: 'multipart/form-data',
        async: true,
        data : function() {
            var data = {};
            var addToData = function(name, val) {
                if(val) {
                    data[name] = val;
                }
            }
            addToData('pname_Aj', $('#pname').val());
            addToData('psection_Aj', $('#psection').val());
            addToData('rinput_Aj', JSON.stringify(fun()));
            addToData('csrfmiddlewaretoken', $("input[name=csrfmiddlewaretoken]").val());
            return data;
        }(),
        success: function (data, textStatus, jqXHR) {
            $('#message').html(data);
            window.location.href = 'myprofile';
            window.location('myprofile');  
            $('.spinner').fadeOut();
        }
    });
}
πŸ‘€Jaromanda X

Leave a comment