1

Lets say that I have HTML code:

<input type="text" id="name" class="form-control" placeholder="Upisi ime">

I get value with php like this: $_POST['name'].

But what If I have JavaScript variable:

var name = "john";

How can I get this JS variable with PHP to use for adding to database?

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
gmaestro
  • 339
  • 7
  • 26

3 Answers3

1

Use a hidden field inside your html form:

<input type="hidden" name="theHiddenName" value="john">
SteAp
  • 11,853
  • 10
  • 53
  • 88
0

If I'm understanding you right, you'll have to use either an AJAX or submit the form using a javascript post.

$(document).ready(function(){
    $('#name').change(function(){
        $.ajax({
            url: "submit.php",
            type: "post",
            data: 'name='+ $('#name').val()
        });
    });
});

http://jsfiddle.net/Wc9W2/

Be sure to click "Run" first. Enter a name and then click off the input field so the change event will fire.

Newbi3
  • 356
  • 1
  • 8
0

You can declare these variables via input box (even hidden input) and using jQuery to grab all of these variables from the input boxes. It'll then seralize them and send them as an object to PHP via $_POST[]; If using this method, jQuery will be already doing the ajax work for you.

Lets say this for an example:

 <form id="myForm">
 <button><input type="text" id="name" class="form-control" placeholder="Upisi ime"></button>
 <input type="hidden" id="presetName" name="javascriptVar">
 </form>
 <div id="result"></div>

and in your jQuery:

$('#myForm').submit( function() {
var name = "john";

$('#presetName').val(name);  // inserting javascript's value
 var senddata = ""; // grabbing all inputs from the form
 senddata = $( this ).serialize(); // packing inputs up
 $.ajax({                                      
    url: 'yourPHP.php',                
   type: 'POST',
   data: senddata,
   success: function(data)   
  {
$('#result').html('<p> Data sent:'+data+'</p>');
      } //end of success
   }); //end of ajax
 event.preventDefault();
});// end submit
Faron
  • 1,255
  • 11
  • 20