将动态表格的数值发送到一个Flask应用程序。

huangapple go评论69阅读模式
英文:

send values of dynamic table to a flask app

问题

I understand you're looking for assistance with your code. It seems you're trying to send data from a dynamic table in an HTML form to your backend using Flask and jQuery. Here are some points to help you:

  1. HTML Structure: Your HTML structure seems fine for the dynamic table.

  2. Adding Rows: Your JavaScript for adding extra rows appears correct.

  3. Sending Data: You are using FormData to collect form data, including the dynamic table data. However, make sure that the names of the input fields in your dynamic table (row[this.name]) match what you expect on the Flask backend.

  4. AJAX Request: Your AJAX request looks mostly correct. Ensure that the url variable (weburl) points to the correct Flask endpoint.

  5. Flask Backend: On the Flask side, you should have a route that listens for POST requests from your frontend. Make sure it's configured to receive and process the data correctly.

  6. Data Format: Be sure to handle the data format correctly on the Flask side. You're sending dynamicData as JSON, so you'll need to parse it using json.loads() in Flask.

  7. Error Handling: Your error handling in the AJAX request is minimal. You may want to implement more robust error handling to provide feedback to the user in case of issues.

  8. Testing: Use console.log statements to debug and see what data is being sent and received. This will help you identify any issues.

  9. Security: Always validate and sanitize user input to prevent security vulnerabilities like SQL injection or cross-site scripting (XSS).

  10. Documentation: Ensure you refer to Flask and jQuery documentation for any specific issues or functionality.

Remember, this kind of development involves both frontend and backend components, so debugging may require checking both sides for issues. It's also a good idea to use developer tools in your web browser to inspect network requests and responses, which can be very helpful for debugging AJAX requests.

Feel free to ask if you have specific questions about any part of your code or encounter issues along the way.

英文:

sorry for this begginer question iam compeltly noob in JQuery i have a flask form thats contain a dynamic table i want to send values of the table to my backend its nearly done but i get values of secound td for etc if i enter the pizza in first td and enter 20 in secound td i get this in my back-end : { "" : "20"}
this is my html ( i cut most the flask form from my cod):

                    <div class="card-body">
                        <h1>New Cafe</h1>
                        <p class="text-muted">Add Your Cafe</p>

                        <form id="my-form" name="cafe" method="post" action=""
                              enctype="multipart/form-data">
                            {{ cafe_form.csrf_token }}
                            {{ ckeditor.load() }}
                            {{ ckeditor.config(name='about') }}
                            {{ cafe_form.name.label }}
                            <div class="input-group mb-3">
                                <span class="input-group-addon"></span>
                                {{ cafe_form.name(class="form-control") }}
                            </div>
                            <div id="data_container">
                                <div id="dynamic-fields">
                                    <table>
                                        <thead>
                                        <tr>
                                            <th>Menu item</th>
                                            <th>Menu item Price in USD $</th>
                                        </tr>
                                        </thead>
                                        <tbody class="p-4">
                                        <tr class="p-2">
                                            <td><input  type="text"></td>
                                            <td><input  type="text"></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </form>
                        <div class="pt-2 pb-2">
                   <button id="submit-btn" class="btn btn-outline-primary px-4">Submit</button>
                            <button id="add_rows" class="btn btn-outline-dark">+</button>
                        </div>
                    </div>

and this is my js for adding extra rows :

>
> $("#add_rows").click(function () {
> // each click on the + button adds a row to the table
> $("#data_container tbody").append(<tr><td><input type="text"></td><td><input type="text"></td></tr>);
> });
> $("#submit_rows").click(function () {
> // obj for storing the inputs, and the n to make unrepeated keys
> let obj = {}, n = 0;
> // loop over the rows
> $("#data_container tbody tr").each(function (ind, tr) {
> // add an array to the object
> obj[r${n}] = [];
> // loop over the inputs of this row
> $(this).find("input").each(function (ind, input) {
> // add the value of the input to the array and make sure to remove any semicolon since
> // we will use it to separate the inputs
> const val = input.value.replace(/;/g, "");
> obj[r${n}].push(val);
> });
> // no need for the array, just join it to a string of values separated by semicolons
> obj[r${n}] = obj[r${n}].join(";");
> // increase the value of n
> n++;
> });
> // log the object to the console so you can see what we are sending
> console.log(obj);
> // send the data to the server, see the console for a logging message for success
> $.post("", obj, (data, status) => console.log("Status: " + status));
> });

and this is the part that i try to send the data to back-end:

    const weburl = "/owner-new-cafe";
    document.getElementById('submit-btn').addEventListener('click', function (event) {
        event.preventDefault();
        submitForm();
    });

    function submitForm() {
        // Collect static form data
        const formData = new FormData(document.getElementById('my-form'));

        // Collect dynamic form data
        const dynamicData = [];
        $('#dynamic-fields tbody tr').each(function () {
            const row = {};
            $(this).find('input').each(function (ind, input) {
                row[this.name] = this.value;
            });
            dynamicData.push(row);
        });

        // Add dynamic form data to FormData object
        formData.append('dynamicData', JSON.stringify(dynamicData));
        document.getElementById("test").innerHTML = formData;

        // Send form data to Flask app using AJAX
        $.ajax({
            url: weburl,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                // Handle response from Flask app
            },
            error: function (xhr) {
                // Handle error
            }
        });

    }

please dont give me just answer iam try to learn i want to know what is my mistakle and what is the best way for doing this thank you so much

答案1

得分: 1

I Fix my problem one problem was when i put the button for add extra row for my dynamic table inside the flask form div so when i click each of submit button Ajax send two post request to my backend or when user just wan to add row again it send a post request and it act like a submit button some how
其他问题是我没有为动态表单的输入指定名称,感谢 @Swati

so in this case i decide to have two div one for flask form and other one for my dynamic form like this :
因此,在这种情况下,我决定有两个 div,一个用于 Flask 表单,另一个用于我的动态表单,就像这样:

<div class="card col-12 col-md-6 center-block">
    <div class="card-body">
        <h1>New Cafe</h1>
        <p class="text-muted">Add Your Cafe</p>
        <!-- Flask form -->
            <form id="my-form" name="cafe" method="post" action="" enctype="multipart/form-data">
                            {{ cafe_form.csrf_token }}
                            {{ ckeditor.load() }}
                            {{ ckeditor.config(name='about') }}
                            {{ cafe_form.name.label }}
                            <div class="input-group mb-3">
                                <span class="input-group-addon"></span>
                                {{ cafe_form.name(class="form-control") }}
                            </div>       
                            <div class="pt-2 pb-2 flex">
                                {{ cafe_form.submit(id="submit_rows", class="btn btn-outline-primary px-4") }}
                            </div>
               <div class="card col-12 col-md-6 center-block">
                    <div class="card-body">
                        <div id="data_container">
                            <div id="dynamic-fields">
                                <table>
                                    <thead>
                                    <tr>
                                        <th>Menu item</th>
                                        <th>Menu item Price in USD $</th>
                                    </tr>
                                    </thead>
                                    <tbody class="p-4">
                                    <tr class="p-2">
                                        <td><label>
                                            <input class="input-group mb-3" name="item" type="text">
                                        </label></td>
                                        <td><label>
                                            <input class="input-group mb-3" name="price" type="text">
                                        </label></td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                            <button id="add_rows" class="flex btn btn-outline-dark">+</button>
                            </div>

and just use this JQuery cod to add extra row in dynamic form

// dynamic row
$("#add_rows").click(function() {
// each click on the + button adds a row to the table
$("#data_container tbody").append(<tr><td><input class="input-group mb-3" name="item" type="text"></td><td><input class="input-group mb-3" name="price" type="text"></td></tr>);
});
$("#submit_rows").click(function() {
// obj for storing the inputs, and the n to make unrepeated keys
var obj = {}, n = 0;
// loop over the rows
$("#data_container tbody tr").each(function() {
// add an array to the object
obj[r${n}] = [];
// loop over the inputs of this row
$(this).find("input").each(function(ind, input) {
// add the value of the input to the array and make sure to remove any semicolon since
// we will use it to separate the inputs
var val = input.value.replace(/;/g, "");
obj[r${n}].push(val);
});
// no need for the array, just join it to a string of values separated by semicolons
obj[r${n}] = obj[r${n}].join(";");
// increase the value of n
n++;
});
// log the object to the console so you can see what we are sending
console.log(obj);
// send the data to the server, see the console for a logging message for success
$.post("", obj, (data, status) => console.log("Status: " + status));
});

in my flask app route i get the values of both list with using request.form.items()and i think we can change it to dict by using to_dict in this case my cod is :

@private.route('//owner-new-cafe', methods=["POST", "GET"])
@login_required
@confirmed_only
@owner_only
def owner_add_cafe(city):
if request.method == "POST" and cafe_form.validate():
print(request.form)
for item in request.form.items():
print(item)
return "Job Done";

英文:

I Fix my problem one problem was when i put the button for add extra row for my dynamic table inside the flask form div so when i click each of submit button Ajax send two post request to my backend or when user just wan to add row again it send a post request and it act like a submit button some how
other problem was i dont assis the name for input for dynamic forom thank to @Swati

so in this case i decide to have two div one for flask form and other one for my dynamic form like this :

<div class="card-group mb-0">

 &lt;div class=&quot;card col-12 col-md-6 center-block&quot;&gt;
     &lt;div class=&quot;card-body&quot;&gt;
        &lt;h1&gt;New Cafe&lt;/h1&gt;
        &lt;p class=&quot;text-muted&quot;&gt;Add Your Cafe&lt;/p&gt;
        &lt;!-- Flask form --&gt;
            &lt;form id=&quot;my-form&quot; name=&quot;cafe&quot; method=&quot;post&quot; action=&quot;&quot; enctype=&quot;multipart/form-data&quot;&gt;
                            {{ cafe_form.csrf_token }}
                            {{ ckeditor.load() }}
                            {{ ckeditor.config(name=&#39;about&#39;) }}
                            {{ cafe_form.name.label }}
                            &lt;div class=&quot;input-group mb-3&quot;&gt;
                                &lt;span class=&quot;input-group-addon&quot;&gt;&lt;/span&gt;
                                {{ cafe_form.name(class=&quot;form-control&quot;) }}
                            &lt;/div&gt;       
                            &lt;div class=&quot;pt-2 pb-2 flex&quot;&gt;
                                {{ cafe_form.submit(id=&quot;submit_rows&quot;, class=&quot;btn btn-outline-primary px-4&quot;) }}
                            &lt;/div&gt;
               &lt;div class=&quot;card col-12 col-md-6 center-block&quot;&gt;
                    &lt;div class=&quot;card-body&quot;&gt;
                        &lt;div id=&quot;data_container&quot;&gt;
                            &lt;div id=&quot;dynamic-fields&quot;&gt;
                                &lt;table&gt;
                                    &lt;thead&gt;
                                    &lt;tr&gt;
                                        &lt;th&gt;Menu item&lt;/th&gt;
                                        &lt;th&gt;Menu item Price in USD $&lt;/th&gt;
                                    &lt;/tr&gt;
                                    &lt;/thead&gt;
                                    &lt;tbody class=&quot;p-4&quot;&gt;
                                    &lt;tr class=&quot;p-2&quot;&gt;
                                        &lt;td&gt;&lt;label&gt;
                                            &lt;input class=&quot;input-group mb-3&quot; name=&quot;item&quot; type=&quot;text&quot;&gt;
                                        &lt;/label&gt;&lt;/td&gt;
                                        &lt;td&gt;&lt;label&gt;
                                            &lt;input class=&quot;input-group mb-3&quot; name=&quot;price&quot; type=&quot;text&quot;&gt;
                                        &lt;/label&gt;&lt;/td&gt;
                                    &lt;/tr&gt;
                                    &lt;/tbody&gt;
                                &lt;/table&gt;
                            &lt;/div&gt;
                            &lt;button id=&quot;add_rows&quot; class=&quot;flex btn btn-outline-dark&quot;&gt;+&lt;/button&gt;
                            &lt;/div&gt;

and just use this JQuery cod to add extra row in dynamic form

> // dynamic row
> $("#add_rows").click(function() {
> // each click on the + button adds a row to the table
> $("#data_container tbody").append(&lt;tr&gt;&lt;td&gt;&lt;input class=&quot;input-group mb-3&quot;
&gt; name=&quot;item&quot; type=&quot;text&quot;&gt;&lt;/td&gt;&lt;td&gt;&lt;input
&gt; class=&quot;input-group mb-3&quot; name=&quot;price&quot; type=&quot;text&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
);
> });
> $("#submit_rows").click(function() {
> // obj for storing the inputs, and the n to make unrepeated keys
> var obj = {}, n = 0;
> // loop over the rows
> $("#data_container tbody tr").each(function() {
> // add an array to the object
> obj[r${n}] = [];
> // loop over the inputs of this row
> $(this).find("input").each(function(ind, input) {
> // add the value of the input to the array and make sure to remove any semicolon since
> // we will use it to separate the inputs
> var val = input.value.replace(/;/g, "");
> obj[r${n}].push(val);
> });
> // no need for the array, just join it to a string of values separated by semicolons
> obj[r${n}] = obj[r${n}].join(";");
> // increase the value of n
> n++;
> });
> // log the object to the console so you can see what we are sending
> console.log(obj);
> // send the data to the server, see the console for a logging message for success
> $.post("", obj, (data, status) => console.log("Status: " + status));
> });

in my flask app route i get the values of both list with using request.form.items()and i think we can change it to dict by using to_dict in this case my cod is :

@private.route(&#39;/&lt;city&gt;/owner-new-cafe&#39;, methods=[&quot;POST&quot;, &quot;GET&quot;])
@login_required
@confirmed_only
@owner_only
def owner_add_cafe(city):
    if request.method == &quot;POST&quot; and cafe_form.validate():
        print(request.form)
    for item in request.form.items():
        print(item)
    return &quot;Job Done&quot;

huangapple
  • 本文由 发表于 2023年5月21日 02:52:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定