简体   繁体   中英

Send JS variable to PHP

I would take the value using getElementById() and pass to a variable on PHP.

<script>
function addMachine() {
  var ip = document.getElementById('ipTextBox').value;
  document.getElementById('ipTextBox').submit;
}
<\script>

The HTML looks like that

<div class="container">
     <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMachine">
     <div class="modal fade" id="addMachine" role="dialog">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add new machine</h4>
                </div>
                <div class="modal-body">
                    <label>Insert machine IP<input id="ipTextBox"></input></label>
                </div>
                <div class="modal-footer">
                     <button type="button" class="btn btn-default" data-dismiss="modal" onclick="addMachine()">ADD</button>
                </div>
            </div>
        </div>
    </div>
<\div>

I don't have any ideas on how to pass this to a PHP variable.

PHP is a backend language used to render HTML and send it to the client on page load. And Javascript is a client side language. If you want to send variables from JS to PHP, basically sending information from the client to the server without page reload, you need to use AJAX:

AJAX stands for "Asynchronous JavaScript and XML". Although the name includes XML, JSON is more often used due to it's simpler formatting and lower redundancy. AJAX allows the user to communicate with external resources without reloading the webpage. Stackoverflow's documentation on Javascript AJAX

  • With AJAX

I have made a post on the documentation page, here it is. I hope it helps you understand how it works.

This function runs an AJAX call using GET allowing us to send parameters (object) to a file (string) and launch a callback (function) when the request has been ended.

function ajax(file, params, callback) {

  var url = file + '?';

  // loop through object and assemble the url
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    }
    notFirst = true;
  }

  // create a AJAX call with url as parameter
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      callback(xmlhttp.responseText);
    }
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

Here's how we use it:

ajax('cars.php', {type:"Volvo", model:"300", color:"purple"}, function(response) {
  // add here the code to be executed when data comes back to this page      
  // for example console.log(response) will show the AJAX response in console
});

And the following shows how to retreive the url parameters in cars.php :

if(isset($_REQUEST['type'], $_REQUEST['model'], $_REQUEST['color'])) {
  // they are set, we can use them !
  $response = 'The color of your car is ' . $_REQUEST['color'] . '. ';
  $response .= 'It is a ' . $_REQUEST['type'] . ' model ' . $_REQUEST['model'] . '!';
  echo $response;
}

If you had console.log(response) in callback function the result in console would have been:

The color of your car is purple. It is a Volvo model 300!

  • With a HTML form

In your HTML page you will have to include a form

<form action="get_data.php" method="get">
  Name: <input type="text" name="name"><br>
  E-mail: <input type="text" name="email"><br>
  <input type="submit">
</form>

And in get_data.php (the target file) you'll have to write:

<?php
echo $_GET["name"];
echo $_GET["email"];

This second method however will redirect the user to get_data.php , I personnaly don't really like it and prefer AJAX for its efficiency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM