Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing Javascript variable to PHP on form submission

This question follows from my previous question counting the rows in html table using php. Since I got no working solution, I want to try a new way but dont know how to implement it. I assign unique ID to each dynamic row added using Javascript. So the count variable in Javascript stores the number of rows present in HTML table. When i submit the form, it is processed by savedata.php. Is it possible to automatically pass the Javascript variable count to savedata.php each time the form is submitted.

Following is a short version of my Javascript file that is used to create unique IDs for elements of dynamically created rows.

var count=2;

function addRow()
{


var table=document.getElementById("studenttable");
var row=table.insertRow(-1);
var cell15=row.insertCell(14);

var ipt8 = document.createElement('input');
    ipt8.setAttribute("type", "hidden");
    ipt8.id = "text" + count; 
    ipt8.name = "htmlrow[]";      
    ipt8.value = count;        
    cell15.appendChild(ipt8);
count++;
}

Each time a new row is added, count increments, so just passing it to the PHP file will allow to get the number of rows in HTML table. I want to do it automatically each time the form is submitted.

like image 623
akashaggarwaal Avatar asked Mar 06 '26 12:03

akashaggarwaal


1 Answers

Add this inside your form..

<input name="NumRows" id="NumRows" type="hidden" value="0"/>

And then modify your JS to update the value...

document.getElementById("NumRows").value = count;

Then, in your PHP you can do...

$NumRows = $_REQUEST['NumRows'];

Note that if for some reason NumRows isn't passed with the form (unlikely here but possible elsewhere) then you should do this in PHP...

$NumRows = isset($_REQUEST['NumRows'])?$_REQUEST['NumRows']:0;

Which means "If $_REQUEST['NumRows'] is set, use it, otherwise set $NumRows to 0"

like image 72
Basic Avatar answered Mar 08 '26 00:03

Basic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!