development

JavaScript 변수를 PHP에 어떻게 전달합니까?

big-blog 2020. 6. 26. 07:44
반응형

JavaScript 변수를 PHP에 어떻게 전달합니까?


폼의 숨겨진 입력을 사용하여 JavaScript 변수를 PHP에 전달하고 싶습니다.

하지만 값 얻을 수 $_POST['hidden1']로를 $salarieid. 문제가 있습니까?

코드는 다음과 같습니다.

<script type="text/javascript">
    // View what the user has chosen
    function func_load3(name) {
        var oForm = document.forms["myform"];
        var oSelectBox = oForm.select3;
        var iChoice = oSelectBox.selectedIndex;
        //alert("You have chosen: " + oSelectBox.options[iChoice].text);
        //document.write(oSelectBox.options[iChoice].text);
        var sa = oSelectBox.options[iChoice].text;
        document.getElementById("hidden1").value = sa;
    }
</script>

<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
    <input type="hidden" name="hidden1" id="hidden1" />
</form>

<?php
   $salarieid = $_POST['hidden1'];
   $query = "select * from salarie where salarieid = ".$salarieid;
   echo $query;
   $result = mysql_query($query);
?>

<table>
   Code for displaying the query result.
</table>

현재 페이지 JavaScript 코드에서 현재 페이지 PHP 코드로 변수 값을 전달할 수 없습니다 ... PHP 코드는 서버 측에서 실행되며 클라이언트 측에서 무슨 일이 일어나고 있는지 전혀 모릅니다.

GET 또는 POST 메소드를 사용하여 양식을 제출하는 것과 같은 다른 메커니즘을 사용하여 HTML 양식에서 PHP 코드로 변수를 전달해야합니다.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>

쿠키에 저장하십시오.

$(document).ready(function () {
  createCookie("height", $(window).height(), "10");
});

function createCookie(name, value, days) {
  var expires;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  else {
    expires = "";
  }
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

그리고 PHP로 읽어보십시오 :

<?PHP
   $_COOKIE["height"];
?>

그것은 예쁜 해결책은 아니지만 작동합니다.


JavaScript에서 PHP로 변수를 전달하는 방법에는 여러 가지가 있습니다 (물론 현재 페이지는 아님).

당신은 할 수 있습니다 :

  1. 여기에 명시된 양식으로 정보를 보내십시오 (페이지를 새로 고치게됩니다).
  2. Ajax로 전달하십시오 (여러 게시물이 여기에 있습니다) (페이지를 새로 고치지 않고)
  3. 다음과 같이 XMLHttpRequest 요청을 통해 페이지를 새로 고치지 않고 HTTP 요청을 작성하십시오.

 if (window.XMLHttpRequest){
     xmlhttp = new XMLHttpRequest();
 }

else{
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

나는 이것이 더 멋지게 보이고 모든 변수와 그 밖의 것들을 반복 할 수 있다고 확신하지만 초보자를 쉽게 이해하도록 기본을 유지했습니다.


작업 예제는 다음과 같습니다. php의 동일한 페이지에서 javascript 변수 값을 가져옵니다.

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>

페이지가 사용자에게 전송되기 전에 PHP가 서버에서 실행되고, JavaScript가 수신되면 사용자의 컴퓨터에서 JavaScript가 실행되므로 PHP 스크립트가 이미 실행되었습니다.

JavaScript 값을 PHP 스크립트에 전달하려면 XMLHttpRequest를 수행하여 데이터를 서버로 다시 보내야합니다.

자세한 정보를 위해 따를 수있는 이전 질문은 다음과 같습니다. Ajax Tutorial

이제 양식 값을 서버에 전달해야하는 경우 일반 양식 게시 만 수행 할 수 있지만 동일한 작업을 수행하지만 전체 페이지를 새로 고쳐야합니다.

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

제출을 클릭하면 페이지가 제출되고 제출 된 데이터가 인쇄됩니다.


나는 이것을 스스로 알아 내려고 노력한 다음 문제는 이것이 상황을 되돌아 보는 일종의 역전이라는 것을 깨달았습니다. JavaScript에서 PHP로 전달하는 대신 대부분의 경우 다른 방법으로 이동하는 것이 가장 좋습니다. PHP 코드는 서버에서 실행되며 html 코드 (및 Java 스크립트도 가능)를 만듭니다. 그런 다음 브라우저는 페이지를로드하고 html 및 java 스크립트를 실행합니다.

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.


We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        FB.api('/me?fields=id,first_name,last_name,email', function (result) {
            document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
            console.log(document.cookie);
        });
    }
}

And I've accessed it (in any file) using -

<?php 
    if(isset($_COOKIE['fbdata'])) { 
        echo "welcome ".$_COOKIE['fbdata'];
    }
?>

Here's how I did it (I needed to insert a local timezone into PHP:

<?php
    ob_start();
?>

<script type="text/javascript">

    var d = new Date();
    document.write(d.getTimezoneOffset());
</script>

<?php
    $offset = ob_get_clean();
    print_r($offset);

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.


Your code has a few things wrong with it.

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>

May be you could use jquery serialize() method so that everything will be at one go.

var data=$('#myForm').serialize();

//this way you could get the hidden value as well in the server side.


when your page first loads the PHP code first run and set the complete layout of your webpage. after the page layout, it set the JavaScript load up. now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't it needs to refresh the page. There is only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP. So we use AJAX to interact Javascript with PHP without page reload. AJAX can also be used as an API. one more thing if you have already declared the variable in PHP. before the page load then you can use it with your Javascript example.

<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>

the above code is correct and it will work. but the code below is totally wrong and it will never work.

<script>
    var username = "syed ali";
    var <?php $myname;?> = username;
    alert(myname);
    </script>
  • Pass value from JavaScript to PHP via AJAX

    it is the most secure way to do it. because HTML content can be edited via developer tools and the user can manipulate the data. so it is better to use AJAX if you want security over that variable.if you are a newbie to AJAX please learn AJAX it is very simple.

The best and most secure way to pass JavaScript variable into PHP is via AJAX

simple AJAX example

var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
    $.ajax({
            type: "POST",
            url: "YOUR PHP URL HERE",
            data:userdata, 
            success: function(data){
                console.log(data);
            }
            });
  • PASS value from javascript to php via hidden fields.

otherwise, you can create hidden HTML input inside your form. like

<input type="hidden" id="mydata">

then via jQuery or javaScript pass the value to the hidden field. like

<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>

Now when you submit the form you can get the value in PHP.


This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.

Just set a cookie with the data you want to pass to PHP using javascript in the browser.

Then, simply read this cookie on the PHP side.


We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

So it's better to use the AJAX to parse the JavaScript value into the php Code.

Or alternatively we can make this done with the help of COOKIES in our code.

Thanks & Cheers.

참고URL : https://stackoverflow.com/questions/1917576/how-do-i-pass-javascript-variables-to-php

반응형