简体   繁体   中英

Submitting all forms on a page with JavaScript using ajax at once to Django

I have a page with multiple forms that have a guid attached to the id. I wrote this JavaScript from an amalgamation of stack post. I'm not that great at JavaScript.

When I submit my form some of my form text boxes disappear, and the data passed to django has no post values. If I log the form right before I send it serialized with ajax using console.log(formData[0]); it logs the form data and all of the elements.

When i print out the post values, and return the post values to the page using django its completely blank. The submission isn't serializing the forms. I assume this is because they exist as an array of forms attached to the main generated form frmCollector. When I submit its null to django. How can I combine all forms and use an ajax submit to send as a object to django. I would be ok with it building a json object. The forms have unique uuids so I don't know what those are. I could build a list but I'm sure there is a more efficient way to do this in javascript.

Here is the full script code so far:

<script>
    function submitAllDocumentForms() {
        var alldata = {};

        $("form").each(function(i, form){

          var current_data = $(form).serializeArray();
          console.log($(form).serializeArray());  
          alldata[$(form).prop("id")]  = current_data;

        });

        alert(JSON.stringify(alldata));

        $.ajax({
          type:'POST',
          url:'save_stacks/',
          data: JSON.stringify(alldata),
          success: function(response) {
           console.log(response);
          }
        });
    }

        var stack_name = "";
        var stack_id_out = "";
        var globalWidth = "";

        var stacksHash = {};

        function guid() {
          function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
              .toString(16)
              .substring(1);
          }
          return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
        }

        function generate_stack_list(idobject){
            var update_list_html = "";
            $.each(stacksHash, function(i, item) {
                update_list_html += '<option value="'+stacksHash[i].stackid+'">'+stacksHash[i].stackid+'</option>';
            }); 
            var id_out = idobject.id.replace(/SecurityGroup/g, "stack_name");
            document.getElementById(id_out).innerHTML = update_list_html;
        }

        function generate_stack(id){
            var stackName = prompt("Please enter your stack name", "storm-nimbus");
            var uuid = guid();

            var id_out = id.replace(/UUID/g, uuid);
            id_out = id_out.replace(/Hide/g, "");
            id_out = id_out.replace(/StackName/g, stackName);
            //stack_ids.set("stackid", id_out);

            stacksHash[id_out]= {"stackid":id_out};
            stack_id_out = id_out;
            var rawFile = new XMLHttpRequest();

            rawFile.open("GET", "{% static 'divTemplates/stack.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var allText = rawFile.responseText;

                        var html_out = allText.replace(/UUID/g, uuid);  

                        var html_out_final = html_out.replace(/STACKNAME/g, id_out); 

                        var current_html = document.getElementById("dynamic_content").outerHTML;

                        document.getElementById("dynamic_content").outerHTML = html_out_final + current_html;

                        globalWidthid = "#"+uuid;
                        globalWidth = $( globalWidthid ).css( "width" );

                    }
                }
            }
            rawFile.send(null);

            //generate multiple list options and software options for the stack
            var html_anaconda_options = "";
            var second_index_position = "";
            var first_index_position = "";
            var anaconda_data = "";
            var number_of_anacondas = "";

            options_id_anaconda = "#SoftwareTab-Anaconda-"+uuid;
            options_id_anaconda_input = "#SoftwareTab-Anaconda-Search-"+uuid;
            options_id_anaconda_links = "#SoftwareTab-Anaconda-Links-"+uuid;

            $.get( "anaconda/", function( data ) {
                anaconda_data = data[0];
                var count = 0;
                $.each(data, function(index) {
                    $.each(data[index], function(index2) {
                        number_of_anacondas++;
                        count++;
                        if(count < "3000"){
                            add_html_options(data[index][index2]);
                            second_index_position = index2;
                            first_index_position = index;

                        }
                    });                 
                }); 
                set_html_anaconda_options();
            });

            function add_html_options(data){
                html_anaconda_options += "<option value='"+data.package+"-"+data.version+"'>"+data.package +"-"+ data.version +"-"+ data.os +"-"+ data.channel +"-"+"</option>";            
            }



            function set_html_anaconda_options(){
                $( options_id_anaconda ).html(html_anaconda_options);
                //console.log(anaconda_data[first_index_position][second_index_position]);
                $( options_id_anaconda_links ).html( "<p style='float:right;'>"+first_index_position + " - " + second_index_position + " of " + number_of_anacondas + "<button style='margin-left:5px;margin-top:5px;' class='btn btn-success' id='anaconda-link-next-"+uuid+"+"+second_index_position+"' onclick='next_anaconda(this)' href='#'>"+" Next "+second_index_position+"</button></p>");
            }
        }

        function next_anaconda(next_value_starting_point){

            var id_tag_information = next_value_starting_point.id.replace(/anaconda-link-next-/g, "");
            var uuid = id_tag_information.split("+")[0];
            var number_of_range = id_tag_information.split("+")[1];
            var next_max = id_tag_information.split("+")[1] * 2;

            var html_anaconda_options = "";
            var anaconda_data = "";
            var number_of_anacondas = "";
            var second_index_position = "";
            var first_index_position = "";

            $( options_id_anaconda ).html("");

            options_id_anaconda = "#SoftwareTab-Anaconda-"+uuid;
            options_id_anaconda_input = "#SoftwareTab-Anaconda-Search-"+uuid;
            options_id_anaconda_links = "#SoftwareTab-Anaconda-Links-"+uuid;

            $.get( "anaconda/", function( data ) {

                anaconda_data = data;
                var count = number_of_range;
                $.each(data, function(index) {
                    $.each(data[index], function(index2) {
                        number_of_anacondas++;
                        if ( count == index2 ){
                            count++;
                            if( count < next_max){
                                    add_html_options_update(data[index][index2]);
                                    second_index_position = count;
                                    first_index_position = next_max;
                            }
                        }
                    });                 
                }); 
                set_html_anaconda_options_update();
            }); 
            function add_html_options_update(data){
                html_anaconda_options += "<option value='"+data.package+"-"+data.version+"'>"+data.package +"-"+ data.version +"-"+ data.os +"-"+ data.channel +"-"+"</option>";            
            }
            function set_html_anaconda_options_update(){
                $( options_id_anaconda ).html(html_anaconda_options);
                var next_max_count = second_index_position *2;
                $( options_id_anaconda_links ).html("<p style='float:right;'>"+first_index_position + " - " + next_max_count + " of " + number_of_anacondas + "<button class='btn btn-success' style='margin-left:5px;margin-top:5px;' id='anaconda-link-next-"+uuid+"+"+second_index_position+"' onclick='next_anaconda(this)' href='#'>"+" Next "+second_index_position+"</button></p>");
            }

        }
        function delete_stack(id){
            var answer = prompt("Are you sure?", "yes");
            if (answer == "yes"){
                id = "#"+id;
                $( id ).remove();       
            }else{
            }
        }

        function delete_blockdevice(deviceObject){
            var answer = prompt("Are you sure?", "yes");
            if (answer == "yes"){
                var id = deviceObject.id.replace(/DB/g, "");  
                id = "#"+id;
                $( id ).remove();       
            }else{
            }

        }   
        //this is the code that generates a block device div form
        //uses 
        function generate_blockdevice(idObject){
            var bd_uuid = guid();
            var rawFile = new XMLHttpRequest();
            var stackID = idObject.id.replace(/BD/g, "");
            var contentID = "block_device_content-"+ stackID;
            rawFile.open("GET", "{% static 'divTemplates/blockdevice.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var bdallText = rawFile.responseText;
                        var insert_uuid = stackID + "-bd_uuid-" + bd_uuid;
                        var html_out = bdallText.replace(/BDUUID/g, insert_uuid);

                        var current_html = document.getElementById(contentID).outerHTML;

                        document.getElementById(contentID).outerHTML = html_out + current_html;
                    }
                }
            }
            rawFile.send(null);     

        }   

            //this deletes a block device
        function delete_generate_security_group(deviceObject){
            var answer = prompt("Are you sure?", "yes");
            if (answer == "yes"){
                var id = deviceObject.id.replace(/DB/g, "");  
                id = "#"+id;
                $( id ).remove();       
            }else{
            }

        }   
        //this is the code that generates a block device div form
        //uses 
        function generate_security_group(idObject){
            var sg_uuid = guid();
            var rawFile = new XMLHttpRequest();
            var stackID = idObject.id.replace(/SG/g, "");
            var contentID = "security_group_content-"+ stackID;

            rawFile.open("GET", "{% static 'divTemplates/securitygroup.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var sgallText = rawFile.responseText;
                        var insert_uuid = stackID + "-sg_uuid-" + sg_uuid;
                        var html_out = sgallText.replace(/SGUUID/g, insert_uuid);  
                        var current_html = document.getElementById(contentID).outerHTML;
                        document.getElementById(contentID).outerHTML = html_out + current_html;
                    }
                }
            }
            rawFile.send(null);     

        }       


        function generate_envvar(idObject){
            var ev_uuid = guid();
            var rawFile = new XMLHttpRequest();
            var stackID = idObject.id.replace(/EV/g, "");
            var contentID = "evn-variable-data-"+ stackID;

            rawFile.open("GET", "{% static 'divTemplates/envvar.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var evallText = rawFile.responseText;
                        var insert_uuid = stackID + "-ev_uuid-" + ev_uuid;
                        var html_out = evallText.replace(/EVUUID/g, insert_uuid);  
                        var current_html = document.getElementById(contentID).outerHTML;
                        document.getElementById(contentID).outerHTML = html_out + current_html;
                    }
                }
            }
            rawFile.send(null);     

        }   


        function disable_tab(passed){

            var id = passed.id.replace(/link-/g, "");

            var pres_id1 = "#"+"presentation1-"+id;
            var pres_id2 = "#"+"presentation2-"+id;
            var pres_id3 = "#"+"presentation3-"+id;
            var pres_id4 = "#"+"presentation4-"+id;
            var pres_id5 = "#"+"presentation5-"+id;
            var pres_id6 = "#"+"presentation6-"+id;
            var pres_id7 = "#"+"presentation7-"+id;
            var pres_id8 = "#"+"presentation8-"+id;
            var pres_id9 = "#"+"presentation9-"+id;
            var pres_id10 = "#"+"presentation10-"+id;
            var pres_id11 = "#"+"presentation11-"+id;
            var pres_id12 = "#"+"presentation12-"+id;
            var pres_id13 = "#"+"presentation13-"+id;
            var pres_id14 = "#"+"presentation14-"+id;

            var main_id = "#"+id;
            var link_id = "#linl-"+id;
            var finalId = "#contentPane-" + id;
            var width=$( main_id ).css( "width" );

            console.log(main_id);

            console.log(width);
            console.log(globalWidth);
            if( width==globalWidth ){
                $( main_id ).css( "width", "600px");
                $( link_id ).css( "background-color", "#FFF");


            }

            if( width=="600px"){
                $( main_id ).css( "width", globalWidth );
                $( link_id ).css( "background-color", "#FFF");
            }

            $(pres_id1).fadeToggle( "fast", function() {}); 
            $(pres_id2).fadeToggle( "fast", function() {}); 
            $(pres_id3).fadeToggle( "fast", function() {}); 
            $(pres_id4).fadeToggle( "fast", function() {}); 
            $(pres_id5).fadeToggle( "fast", function() {}); 
            $(pres_id6).fadeToggle( "fast", function() {}); 
            $(pres_id7).fadeToggle( "fast", function() {}); 
            $(pres_id8).fadeToggle( "fast", function() {}); 
            $(pres_id9).fadeToggle( "fast", function() {}); 
            $(pres_id10).fadeToggle( "fast", function() {});    
            $(pres_id11).fadeToggle( "fast", function() {});    
            $(pres_id12).fadeToggle( "fast", function() {});    
            $(pres_id13).fadeToggle( "fast", function() {});    
            $(pres_id14).fadeToggle( "fast", function() {});        
            $(finalId).fadeToggle( "fast", function() {});      

        }
    </script>

here is an example of the dynamic html that is loaded

<div style="width:98%;padding:15px;margin-left:15px;margin-top:15px;margin-bottom:15px;position:relative;background-color:#FFF;border-radius:15px;" id="UUID">
<span class="glyphicon glyphicon-eye-open" style="color: #00db92;float:left;margin-right:5px;margin-top:5px;font-size: 35px;" aria-hidden="true"></span>

<ul class="nav nav-tabs" role="tablist">
<li id="presentation1-UUID" role="presentation">
<a id="presentation2-UUID" href="#AutoScalingGroup-UUID" aria-controls="AutoScalingGroup-UUID" role="tab" data-toggle="tab">Auto Scaling Group</a></li>
<li id="presentation3-UUID" role="presentation">
<a id="presentation4-UUID" href="#LaunchConfigTab-UUID" aria-controls="LaunchConfigTab-UUID" role="tab" data-toggle="tab">Launch Config</a></li>
<li id="presentation5-UUID" role="presentation">
<a id="presentation6-UUID" href="#UserDataTab-UUID" aria-controls="UserDataTab-UUID" role="tab" data-toggle="tab">User Data</a></li>
<li id="presentation7-UUID" role="presentation">
<a id="presentation8-UUID" href="#BlockDevicesTab-UUID" aria-controls="BlockDevicesTab-UUID" role="tab" data-toggle="tab">Block Devices</a></li>
<li id="presentation9-UUID" role="presentation">
<a id="presentation10-UUID" href="#SecurityGroupsTab-UUID" aria-controls="SecurityGroupsTab-UUID" role="tab" data-toggle="tab">FStack Connections</a></li>
<li id="presentation11-UUID" role="presentation">
<a id="presentation12-UUID" href="#SoftwareTab-UUID" aria-controls="SoftwareTab-UUID" role="tab" data-toggle="tab">Software</a>
</li>
<li id="presentation13-UUID" role="presentation">
<a id="presentation14-UUID" href="#Administration-UUID" aria-controls="Administration-UUID" role="tab" data-toggle="tab">Administration</a>
</li>
<li id="hide-UUID" role="presentation">
<a href="#" id="link-UUID" onclick="disable_tab(this);" data-toggle="tooltip" data-placement="top" title="Click this to toggle the stack options.">STACKNAME</a></li>
<li id="presentation11-UUID" role="presentation"><a id="generate-button" class="btn btn-danger" onclick="delete_stack('UUID')" style="float:right";>Delete</a></li>
</ul>

</center>

<div class="tab-content" style="" id="contentPane-UUID">
    <div role="tabpanel" class="tab-pane fade" id="AutoScalingGroup-UUID">
        <div style="padding:15px;width:250px;">
            <form id="AutoScalingGroup-UUID">
                <label for="AutoScalingGroup-UUID">AutoScalingGroup</label>
                <div class="form-group"><label for="name">name</label>
                <input type="name" class="form-control" id="name-UUID" placeholder="ExampleASGConfig" data-toggle="tooltip" data-placement="top" title="name (str) &#x2013; Name of the auto scaling group to create.">
                </div>
                <div class="form-group">
                <label for="availability_zones-UUID">availability_zones</label>
                <select class="form-control" id="availability_zones-UUID" placeholder="us-west-2" data-toggle="tooltip" data-placement="top" title="availability_zones (list) &#x2013; List of availability zones (required).">
                <option value="us-east-1">us-east-1:US East (N. Virginia)</option>
                <option value="us-east-2">us-east-2:US East (Ohio)</option>
                <option value="us-west-1">us-west-1:US West (N. California)</option>
                <option value="us-west-2">us-west-2:US West (Oregon)</option>
                <option value="ca-central-1">ca-central-1:Canada (Central)</option>
                <option value="eu-west-1">eu-west-1:EU (Ireland)</option>
                <option value="eu-central-1">eu-central-1:EU (Frankfurt)</option>
                <option value="eu-west-2">eu-west-2:EU (London)</option>
                <option value="ap-northeast-1">ap-northeast-1:Asia Pacific (Tokyo)</option>
                <option value="ap-northeast-2">ap-northeast-2:Asia Pacific (Seoul)</option>
                <option value="ap-southeast-1">ap-southeast-1:Asia Pacific (Singapore)</option>
                <option value="ap-southeast-2">ap-southeast-2:Asia Pacific (Sydney)</option>
                <option value="ap-south-1">ap-south-1:Asia Pacific (Mumbai)</option>
                <option value="sa-east-1">sa-east-1:South America (São Paulo)</option>
                </select>
                </div>

                <div class="form-group">
                <label for="default_cooldown-UUID">default_cooldown</label>
                <input type="default_cooldown" class="form-control" id="default_cooldown-UUID" placeholder="300" data-toggle="tooltip" data-placement="top" title="default_cooldown (int) &#x2013; Number of seconds after a Scaling Activity completes before any further scaling activities can start."></div>

                <div class="form-group">
                <label for="desired_capacity-UUID">desired_capacity</label>
                <input type="desired_capacity" class="form-control" id="desired_capacity-UUID" placeholder="1" data-toggle="tooltip" data-placement="top" title="desired_capacity (int) &#x2013; The desired capacity for the group."></div>

                <div class="form-group">
                <label for="health_check_period-UUID">health_check_period</label>
                <input type="health_check_period" class="form-control" id="health_check_period-UUID" placeholder="300" data-toggle="tooltip" data-placement="top" title="health_check_period str &#x2013; Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health."></div>

                <div class="form-group">
                <label for="health_check_type-UUID">health_check_type</label>
                <input type="health_check_type" class="form-control" id="health_check_type-UUID" placeholder="EC2" data-toggle="tooltip" data-placement="top" title="health_check_type str &#x2013; The service you want the health status from, Amazon EC2 or Elastic Load Balancer."></div>

                <div class="form-group">
                <label for="launch_config-UUID">launch_config</label>
                <input type="launch_config" class="form-control" id="launch_config-UUID" placeholder="launch_config_name" data-toggle="tooltip" data-placement="top" title="launch_config str or LaunchConfiguration &#x2013; Name of launch configuration required."></div>

                <div class="form-group">
                <label for="load_balancers-UUID">load_balancers</label>
                <input type="load_balancers" class="form-control" id="load_balancers-UUID" placeholder="" data-toggle="tooltip" data-placement="top" title="load_balancers list &#x2013; List of load balancers."></div>

                <div class="form-group">
                <label for="max_size-UUID">max_size</label>
                <input type="max_size" class="form-control" id="max_size-UUID" placeholder="1" data-toggle="tooltip" data-placement="top" title="max_size (int) &#x2013; Maximum size of group required."></div>

                <div class="form-group">
                <label for="min_size-UUID">min_size</label>
                <input type="min_size" class="form-control" id="min_size-UUID" placeholder="1" data-toggle="tooltip" data-placement="top" title="min_size (int) &#x2013; Minimum size of group required."></div>

                <div class="form-group">
                <label for="placement_group-UUID">placement_group</label>
                <input type="placement_group" class="form-control" id="placement_group-UUID" placeholder="t1.micro" data-toggle="" data-placement="top" title="placement_group str &#x2013; Physical location of your cluster placement group created in Amazon EC2."></div>

                <div class="form-group">
                <label for="vpc_zone_identifier-UUID">vpc_zone_identifier</label>
                <input type="vpc_zone_identifier" class="form-control" id="vpc_zone_identifier-UUID" placeholder="sub-00000,sub-11111" data-toggle="tooltip" data-placement="top" title="vpc_zone_identifier str or list &#x2013; A comma-separated string or python list of the subnet identifiers of the Virtual Private Cloud."></div>

I had to truncate some of the html to fit the post but you get the idea.

Your collect function can be simplified and then you can post all the data as json either with serializeArray or serialize, for example:

var alldata = {};

$("form").each(function(i, form){
  var current_data = $(form).serializeArray();
  alldata[$(form).prop("id")]  = current_data;
});
alert(JSON.stringify(alldata));

$.ajax({
  //your parameters here: url, etc.
  url: 'save_stacks',
  type: 'post',
  dataType: 'json',
  data: alldata,
  success: function(response) {
    //handling code
  }
});

https://jsfiddle.net/1pLn4hw1/

You will likely have to adapt your handling code in the backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM