0

I am pulling values form a dynamic table to JSON but somehow I am Unable to POST JSON data to PHP. Where am going wrong? I would greatly appreciate some assistance, I would eventually like to INSERT to MSQL db

Error on test.php => Notice: Undefined index: p_row

<script type="text/javascript">
    var table = document.getElementById('table'),
        rows = table.getElementsByTagName('tr'),
        i, j, cells, OS_d, roleApp_d, Men_d, vcpu_d, Val_d, Per_d, hw_d;

    var p_row = '[';
    for (i = 1, j = rows.length; i < j; ++i) {
        cells = rows[i].getElementsByTagName('td');
        if (!cells.length) {
            continue;
        }

        p_row += "{";
        p_row += '"' + cells[1].firstChild.value + '",';
        p_row += '"' + cells[2].firstChild.value + '",';
        p_row += '"' + cells[3].firstChild.value + '",';
        p_row += '"' + cells[4].firstChild.value + '",';
        p_row += '"' + cells[5].firstChild.value + '",';
        p_row += '"' + cells[6].firstChild.value + '",';
        p_row += '},';

    }
    p_row = (p_row).replace(new RegExp("[,]+$"), "");
    p_row += ']';

    $.ajax({
        url: 'http://localhost/portal/test.php',
        type: 'POST',
        content: 'application/json',
        dataType: 'json',
        data: JSON.stringify(p_row),
        success: function (data, status, xhr) {

        }
    });
</script>   

test.php

<?php
    $data = json_decode($_POST["p_row"]);
    echo $_POST["p_row"];
?>
mitkosoft
  • 5,262
  • 1
  • 13
  • 31
  • 3
    1) The JSON you're building is not in a valid format. 2) Don't build JSON manually as a string. Create it in an array or object and then serialise it using `JSON.stringify()` – Rory McCrossan Jan 23 '20 at 17:00
  • Are you manually creating JSON? Don't do that, there are easier ways! – delboy1978uk Jan 23 '20 at 17:01
  • You are only sending the json, not the json in a variable. And, there are much easier ways to make/send json with jquery. – IncredibleHat Jan 23 '20 at 17:01
  • 1
    Logically, trying to `JSON.stringify(aString)` should have already been a noticable code smell when you were writing the code. – Taplar Jan 23 '20 at 17:02
  • Also, related to the PHP side: https://stackoverflow.com/questions/7047870/issue-reading-http-request-body-from-a-json-post-in-php – Taplar Jan 23 '20 at 17:04

0 Answers0