简体   繁体   中英

Javascript Variable in PHP Array Variable?

I'm working on an invoice system. By default it loads with 1 row to input items. If a administrator wants to add additional items they may click a link which executes a JavaScript to add additional rows. This is working great for me.

I submit the form using POST method to the same page. If a user added additional rows using the JavaScript, it loads with the previous amount of rows as when the page was submitted. To do this I used PHP $table_rowcount = count( $_POST["item_details"] ); . Just FYI, the {$table_rowcount} isn't a syntax error as I'm using a template engine.

Everything works great to this point. Administrators can add additional rows to input data and when the page is submitted to itself it loads those number of rows. Perfect. However this is where the problem comes in.

What I need to do is use a method of sticky forms so if there is an error, the page will reload (as it currently does) with variables assigned to each inputs value="" so the administrator wont have to re-enter all the details.

The problem is I do not know how to do this with a combination of JavaScript and PHP. I need to some how get the current number of the row using the for() loop in JavaScript and then use that number in a PHP variable as seen in the tbody of the HTML below for the default 1st row.

Basically if it is the 3rd row and the for() loop will show it as var i = 2 (since array starts at 0), how can I use JavaScript to help me call the PHP variable {$item.2.details} .

I'm assuming I need to use AJAX for this? However I do not know AJAX. I'm hoping someone could assist me with this so myself and others can learn how this is properly done.

Question simply put

How can I use a JavaScript variable to select a PHP array in a HTML file?

JavaScript:

<script type="text/javascript">
window.onload = function loadRows() {
    for( i = 1; i < {$table_rowcount}; i++ ) {

        // Set table id.
        var table = document.getElementById("invoice_items");

        // Count rows.
        var rowCount = table.rows.length;

        // Row to insert into table.
        var row = table.insertRow(rowCount);

        // Cells to insert into row.
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        // Current Row.
        var rowNumber = rowCount + 1;

        // Data in cells.
        cell1.innerHTML = "<textarea name=\"item_details[]\"></textarea>";
        cell2.innerHTML = "<input type=\"text\" name=\"item_quantity[]\" value=\"\" />";
        cell3.innerHTML = "<input type=\"text\" name=\"item_price[]\" value=\"\" />";
    }
}
</script>

HTML:

<form method="post" action="index.php?do=invoices_add">

    <label class="label">
        <div class="left">
            Invoice Items
        </div>
        <table id="invoice_items" cellpadding="0" cellspacing="0" border="0">
            <thead>
                <tr>
                    <td>
                        Item Details
                    </td>
                    <td>
                        Quantity
                    </td>
                    <td>
                        Price
                    </td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <textarea name="item_details[]">{$item.0.details}</textarea>
                    </td>
                    <td>
                        <input type="text" name="item_quantity[]" value="{$item.0.quantity}" />
                    </td>
                    <td>
                        <input type="text" name="item_price[]" value="{$item.0.price}" />
                    </td>
                </tr>
            </tbody>
        </table>
        <a href="#invoice_items" onclick="addRows()">+ Add Item</a>
    </label>
    <br/>

    <label class="label">
        <input type="submit" value="submit" name="submit" />
    </label>

</form>

Just to make sure I understand correctly: You have users who enter new rows, and if there is an error, their newly entered rows are lost, along with the information they typed. Based on that:

My first instinct is to post the form via AJAX, but if you want to go the PHP route, I would recommend researching session based flash messages . You can use session data to send back the values which have already been input, along with additional error messages. I have previously set flash data as one object with property names such as "errors". "errors" would be an array of error messages, but you can also set a property called "additionalItem" and add the newly created items by the user. Then add these to your row iteration in the PHP, avoiding the necessity of using JavaScript to build the rows.

$flashData = Array("additionalItem" => Array());

for ($_PARAMS["addedRows"] as $row) {
    $flashData["additionalItem"] []= Array(
        "rowDetails" => $row['details'],
        "rowQuantity" => $row['quantity'],
        "rowPrice" => $row['price']
    )
}

I would also recommend client side validation where possible. However, I also understand other non-client-side errors can arise.

If you have to do it in JavaScript then I think your best option here is to expose the PHP array you want to iterate over and store it as a JavaScript variable (so either way you will probably need to set flash data).

<script type="text/javascript">
  // I renamed item to items as I am assuming you have an array.
  // This would preferably be an array of items from the server.
  var items = {$items},
      table = document.getElementById("invoice_items");

  window.onload = function loadRows() {
    for (i = 1; i < items.length; i++) {
      var rowCount = table.rows.length,
          row = table.insertRow(rowCount),
          cell1 = row.insertCell(0),
          cell2 = row.insertCell(1),
          cell3 = row.insertCell(2),              
          rowNumber = rowCount + 1;

      cell1.innerHTML = "<textarea name='item_details[]'>" + 
          items[i].details + "</textarea>";
      cell2.innerHTML = "<input type='text' name='item_quantity[]' 
          value='' />";
      cell3.innerHTML = "<input type='text' name='item_price[]' 
          value='' />";
    }
  }
</script>

I hope this helps and that I did not misunderstand the question :)

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