Search code examples
javascripthtmlajaxcoldfusioncfml

How to put ajax array to coldfusion variable?


I'm working on one issue and I need some help. I'm working on HTML code that fills in special machine labels. It is a kind of web page on where people fill in the number of lines and text size, then enter the text of the lines they want the resulting table to contain in each line.

I need advice on how to put ajax array to coldfusion variable.

Here is a small sample of the problem where I sequentially retrieving text from the fields:

for(let a = 1; a <= g_rowCounter; a++){
   text = getVal('i_row-input_' + a);
   g_texts.push(text);
   reqData += "label_"+a+"="+text+"&";
   dataForAjax["label_" + a] = text;
}

Here I would like to put the ajax array in a coldfusion variable:

<cfoutput>#label_1#</cfoutput>

I need to put those ajax arrays to coldfusion variables and than list them to the bottom of the program. You can see it in this photo.

enter image description here

Is there anyone who would encounter a similar problem or know how to solve it?

Thank you for all the answers.

Here is for reference whole code to lock at the problem.

<html>
    <head>
        <meta charset="UTF-8">
        <title>Stitek</title>
        <script
            src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous"></script>
        <style>
            div.c_row-inputs_wrp{
                display: flex;
                flex-direction: column;
            }
            
            input.c_form-input, button.c_form-button, input.c_row-input {
                margin: 4px;
                margin-left: 0px;
            }
            
            button.c_form-button {
                width: 130px;
            }
            
            input.c_form-input, input.c_row-input {
                width: 250px;
            }

            
            
            
            /* styly pro hlavni ramecek (wrapper) */
            div.c_vystup_wrp {
                display: inline-block;
                padding: 0 5mm;
                

                /*odtud se muze menit*/
                border: 1px solid white;
                background-color: black;
                
            }
            
            /* styly pro kontejner (wrapper)) od textu */
            div.c_jeden-radek_wrp {
                display: flex; /*nemenit*/
                
                /*odtud se muze menit*/
                justify-content: center;
            }
            
            /* styly pro jednotlivy radek textu */
            span.c_jeden-radek_text {
                /*odtud se muze menit*/
                color: white;
                font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
                font-weight: bold;
            }
            
        </style>
        
        <script>
            var g_rowCounter = 0;
            var g_texts = [];
            
            function vygenerujInputy(){
                var rowCount = parseInt(getVal('i_row-count'));
                var inputWrp = byId('i_row-inputs_wrp');
                var oneInput = null;
                
                inputWrp.innerHTML = '';
                
                for(let a = 1; a <= rowCount; a++){
                    var defText = '';
                    if(g_texts[a - 1]){
                        defText = g_texts[a - 1];
                    }
                    
                    oneInput = createRowInput(a, defText);

                    inputWrp.appendChild(oneInput);
                }
                
                g_rowCounter = rowCount;
            }

            function createRowInput(number, defText){
                var r = document.createElement('div');
                
                var input = document.createElement('input');
                input.setAttribute('id', 'i_row-input_' + number);
                input.setAttribute('class', 'c_row-input');
                input.setAttribute('name', 'label_' + number);
                input.value = defText;
                
                var numberSpan = document.createElement('span');
                numberSpan.innerHTML = number + ')&nbsp;&nbsp;';
                
                r.appendChild(numberSpan);
                r.appendChild(input);
                
                return r;
            }
            
            function getVal(htmlId){
                var r = byId(htmlId).value;
                return r;
            }   

            function byId(htmlId){
                var r = document.getElementById(htmlId);
                return r;
            }
            
            function VygenerujVystup(){
                
            }

            function vygenerujTabulku(){
                var outputWrp = byId('i_vystupni-div');
                outputWrp.innerHTML = '';

                if(g_rowCounter < 1){
                    window.alert('nejprve zvol počet řádků');
                } else {
                    var textSize = parseInt(getVal('i_velikost-textu'));
                    
                    if(textSize < 6 || textSize > 75){
                        window.alert('velikost textu musi byt v intervalu od 6 do 75 mm');
                    } else {
                        var frameSize = parseInt(getVal('i_sirka-ramecku'));   
                            g_texts = [];

                            var text = '';
                            var oneRowDom = null;
                            var reqData = "?";
                            var dataForAjax = {};

                            for(let a = 1; a <= g_rowCounter; a++){
                                text = getVal('i_row-input_' + a);
                                g_texts.push(text);
                                reqData += "label_"+a+"="+text+"&";
                                dataForAjax["label_" + a] = text;
                            }

                            

                            for(let a = 0; a < g_texts.length; a++){
                                oneRowDom = createWrappedSpan('jeden-radek', g_texts[a], textSize);
                                outputWrp.appendChild(oneRowDom);
                            } 
                            
                            console.log(g_texts);
                            console.log(reqData);
                            console.log(getVal('i_velikost-textu'));

                            dataForAjax.velikostTextu = getVal('i_velikost-textu');
                            dataForAjax.velikostTabulkyWidth = (document.querySelector("#i_vystupni-div").clientWidth + 2) / 0.2645833333333; //:D
                            dataForAjax.velikostTabulkyHeight = (document.querySelector("#i_vystupni-div").clientHeight + 2) / 0.2645833333333;

                            $.ajax({
                                method: "GET",
                                url: "stitek009c.cfm",
                                data: dataForAjax
                            });
                            /*
                            var reqObject = new XMLHttpRequest();
                            reqObject.open("POST", g_texts, true);
                            reqObject.send();*/

                       // }  
                    }
                }
            }

            //kdyz textSize je vetsi nez 0, nastavi se velikost textu podle tohoto cisla. jinak se necha vychozi velikost
            function createWrappedSpan(rawClassName, text, textSize){
                var r = document.createElement('div');
                r.setAttribute('class', 'c_' + rawClassName + '_wrp');

                var span = document.createElement('span');
                span.setAttribute('class', 'c_' + rawClassName + '_text');
                span.innerHTML = text;

                if(textSize > 0){
                    span.style.fontSize = textSize + 'mm';
                }
                
                r.appendChild(span);

                return r;
            }
        </script>
    </head>
    
    <body>
    
      <div>
        <b>Zvol počet řádků štítku &nbsp;&nbsp;</b>
    
        <select name="srows" id="i_row-count" onchange="vygenerujInputy()">
            <option value="0" name="m00" size="50" maxlength="30" type="text">0  
            <option value="1" name="m01" size="50" maxlength="30" type="text">1
            <option value="2" name="m02" size="50" maxlength="30" type="text">2
            <option value="3" name="m03" size="50" maxlength="30" type="text">3
            <option value="4" name="m04" size="50" maxlength="30" type="text">4
            <option value="5" name="m05" size="50" maxlength="30" type="text">5
        </select>
      
        <!--
            Výběr hodnot - počtu řádků - 1 - 5.
        -->
        <br><br>
        <div id="i_row-inputs_wrp" class="c_row-inputs_wrp"></div>
        <br>
        <span>velikost textu (milimetry)&nbsp;&nbsp;</span><input type="number" name="quantity" id="i_velikost-textu" min="6" max="75" range = "6,75" validate = "integer">
        <br>
        <!--
            Velikost textu je omezena od 6ti do 75ti.
        -->
        <br>
        <span>UPRAVIT - velikost tabulky šířka (milimetry)&nbsp;&nbsp;</span><input type="number" id="i_sirka-ramecku" class="c_form-input" list="bodySize">
        <br>  
        <br>
        <span>UPRAVIT - velikost tabulky výška (milimetry)&nbsp;&nbsp;</span><input type="number" id="i_vyska-ramecku" class="c_form-input" list="bodySize">
        <br>

        <br>
            <button onclick="vygenerujTabulku()" class="c_form-button">Náhled štítku</button>
        <br>



    </div>
    <div class="c_vystup_wrp" id="i_vystupni-div"></div>
       <cfform>
    <cfoutput>#label_1#</cfoutput>
      
      <!--
            here is label_1 just like a example
        -->
    
        
            <cf name="swidth" id="i_sirka-ramecku" onchange="vygenerujTabulku()"> 
        </cf>
    </cfform>
        
    </body>
</html>

Solution

  • When you send an ajax GET request to a cfml file as you did to "stitek009c.cfm" , you are sending all the data along as an URL variable to that cfm template. Thus, you are already providing all the ajax data to your stitek009c.cfm template with the variables within the URL scope.

    From what I understand is that you also want to add the cfml generated content and append it to the bottom of your form.

    To achieve that, I'm missing additional code in your jQuery ajax request:

    $.ajax({
        method: "GET",
        url: "stitek009c.cfm",
        data: dataForAjax
    });
    

    That ajax request above misses code for serving the result of your ajax request, which is typically served jQuery's ajax as deferred object with the .done() method. To complete that code I'm providing the additional lines as an example. For further reference, please see jQuery's ajax documentation:

    $.ajax({
        method: "GET",
        url: "stitek009c.cfm",
        data: dataForAjax
        }).done( function( result ) {
            
                //populate div with returned html
                $('#ajaxReturn').html( result.contentHTML );
    
        }).fail( function( e ) { 
                
                //log some info and alert about fail
                console.dir( e.responseText );
                alert('Ops! Something went wrong!');
    
        });
    

    As you can see from the example code above, a html div with the id ajaxReturn will be populated with the returned JSON data, thus you need to add that empty container (<div id="ajaxReturn"></div>) to the bottom of your form right after the div container of id="i_vystupni-div" like so:

    ...
        <div class="c_vystup_wrp" id="i_vystupni-div"></div>
        <div id="ajaxReturn"><!-- this container body will be populated with the genertated data of the stitek009c.cfm --></div>
    </body>
    

    Finally, I'm providing you a sample of how your stitek009c.cfm could look like. This example generates a simple cfdump of the URL scope and returns it as a JSON object:

    <!--- stitek009c.cfm --->
    <cfsavecontent variable="result.contentHTML">
        <!--- generate some cfml code --->
        <cfdump var="#url#">
    </cfsavecontent>
    <cfcontent reset = "true" />
    <cfheader name="content-type" value="application/json" />
    <cfoutput>#serializeJSON( result )#</cfoutput>