简体   繁体   中英

Adding Table Cell Contents to PHP $_POST

From my understanding, the only way to retrieve $_POST data is using the name attribute of the element, like so:

<INPUT type="text" name="txt">

and the PHP portion:

<?php $text = $_POST["txt"]; ?>

I've got a table with cells containing plain text, for example:

<td class="textField" id="txt1"> Some text </td>

Is there anyway to post the text in these table cells and retrieve them using either the class or id? Maybe there is a clever way to get around this? <td> doesn't have a name attribute thus the reason for my question.

Thanks!

You can use ajax, getting values from the table with javascript. JQuery is a good library for this:

http://api.jquery.com/category/ajax/

$_POST and $_GET come from the request. Meaning the browser sends them with the headers and PHP provides an interface to them with $_POST , $_GET , $_COOKIE , and $_REQUEST . The browser doesn't send contents of a table in the request.

If you're trying to make a field 'read-only' you're going about it the wrong way. If a field is read-only you should never trust the browser to re-send that same value.

To retrieve values from many form-fields who all have the same name (because you generate them with a loop in PHP), append brackets to the names of your fields.
Simple example:

<form method="post">
<input type=text name="myfield[]">  
<input type=text name="myfield[]">  
<input type=text name="myfield[]">  
<input type=text name="myfield[]">  
</form>

If you add to your code:

<?php print_r($_POST); ?>  

you'll notice that the $_POST variable is populated with an array named "myfield" having 4 values from $_POST['myfield'][0] to $_POST['myfield'][3]. You may then use a foreach loop in PHP to retrieve all values.

The solution that ended up working for me was to grab the data using jQuery, encode it in JSON, and add it to a serial array of the rest of the form data.

$("#orderForm").submit(function(e) {
    e.preventDefault();

    // Get NON-INPUT table cell data
    var subtotal = new Array();
    $('#priceTable td.subtotal').each(function() {
        subtotal.push($(this).html());
    });

    // Get all INPUT form data and organize as array
    var formData = $(this).serializeArray();

    // Encode with JSON
    var subArray = JSON.stringify(subtotal);

    // Add to formData array
    formData.push({name: 'sub', value: subArray});

    // Submit with AJAX
    $.ajax({
        url: "submitOrder.php",
        data: formData,
        type: 'post',
        success: function(data) {
            alert(data);
        }
    });
});

And on the PHP side:

$subtotals = json_decode($_POST['sub']);

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