akashaggarwaal
akashaggarwaal

Reputation: 189

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.

Upvotes: 3

Views: 2491

Answers (3)

Akash Gupta
Akash Gupta

Reputation: 318

I would suggest never use $_REQUEST, use $_POST for post method forms. If you use $_REQUEST you have no guarantee that the data came from the post data, which leads to security holes in your script. So better use

$NumRows = $_POST['NumRows'];

to access the count value in PHP

Upvotes: 2

myk.
myk.

Reputation: 333

Go for Ajax call. Each time when submit button is clicked make an ajax call and send the required data to the any php page.

here go through these links and they will definitely gonna help u

http://www.w3schools.com/jquery/ajax_post.asp

http://api.jquery.com/jQuery.post/

Upvotes: 0

Basic
Basic

Reputation: 26766

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"

Upvotes: 4

Related Questions