Anushka Agarwal
Anushka Agarwal

Reputation: 127

Passing variable from javascript to php without using window.location

I am dynamically creating text box by clicking on add button.In this I am incrementing a count variable when add button is clicked.How can I get this count value in my PHP file.I have tried window.location but its not working.My code is:

<script>
  var counter=1;
  function generateRow() {
   var count=counter;

    var temp ="<div class='_25'>Answer:<input type='textbox' size='100' id='textbox' name='mytext[]"+counter+"' placeholder='Please enter your answer text here.....'></input><input name='' type='button' value='Delete' /></div>";

    var newdiv = document.createElement('div');
    newdiv.innerHTML = temp + count;

    var yourDiv = document.getElementById('div');

    yourDiv.appendChild(newdiv);

    var js_var=counter++;

    xmlhttp.open("GET","tt.php?js_var="+js_var,true);
    xmlhttp.send(); 
 }
</script>

Upvotes: 0

Views: 156

Answers (3)

jogesh_pi
jogesh_pi

Reputation: 9782

Achieve it like this:

  var counter=1;
  function generateRow() {
   var count=counter;

    var temp ="<div class='_25'>Answer:<input type='textbox' size='100' id='textbox' name='mytext[]"+counter+"' placeholder='Please enter your answer text here.....'></input><input name='' type='button' value='Delete' /></div>";

    var newdiv = document.createElement('div');
    newdiv.innerHTML = temp + count;

    var yourDiv = document.getElementById('div');

    yourDiv.appendChild(newdiv);

    var js_var=counter++;

    // Update your counter Stat in input field
    $('#counter_stat').val( js_var );

    xmlhttp.open("GET","tt.php?js_var="+js_var,true);
    xmlhttp.send(); 
 }

Create a HTML Input tag for your counter value:

// Pass this field's value to PHP
<input type="hidden" name="counter_stat" id="counter_stat" value="1">

Upvotes: 0

Cjmarkham
Cjmarkham

Reputation: 9700

Since you are adding the variable to the url you could get it with PHP's $_GET method.

$_GET['js_var'];

Upvotes: 0

Steve Bals
Steve Bals

Reputation: 1989

in php file

$count_val=$_GET['js_var'];

Upvotes: 2

Related Questions