Pass the value of the php variable. How to pass a variable from JavaScript to PHP

Why is the question of passing a variable from language to language a beginner question? Because it's impossible to do it! Programming languages ​​each work independently. And transfer directly between them is impossible. Now I will explain why.

The fact is that PHP and JavaScript are only conditionally related. PHP runs on the server and JavaScript runs in the browser.

Let me remind you of the Internet algorithm. That is, what happens when you request an address...

  • The browser generates request headers, appends some kind of important information about yourself and sends them to this address.
  • The server receives the headers and understands that the document needs to be sent. He understands that it is not a document that is being requested, but a program. Then he launches this program and gives it all the data that he received from the browser.
  • The program (php script) runs, runs and simply prints the result of its work. The result of the work can be an HTML page with JavaScript scripts included. But we remember that in this moment PHP and JavaScript work for it and are no different from any other data. Just letters.
  • The server receives what the program printed. Attaches the response headers and sends them all to the requesting browser.
  • The browser receives the page code and displays it. Loads more necessary files(js, css, images), applies them to the html code. And only now the JavaScript built into the browser is turned on.
  • If you look closely at this order of work, you can answer the question

    How to pass a variable from PHP to JavaScript?

    Needed at runtime PHP script just generate such text so that it can then be executed in the browser. For example.

    Asynchronously passing a variable from JavaScript to PHP

    That means using Ajax. Essentially, the same thing happens as in the previous case, but the browser page does not reload. The easiest way to illustrate this is using the .

    var message = "Hello, server!"; $..php", (message:message), function(data) ( alert("Server responded: "+data); ));

    As you can see, everything is even simpler. There is no need to use the encodeURIComponent function; jQuery does it for us. We are describing a function that takes the server response and adds it to the data variable. If index.php simply returns the value of the $_GET variable, then we will see an alert with the text “The server responded: Hello, server!”.

    Broadcast complex objects from php to javascript

    We remember that when generating JavaScript from php, you need to adhere to JavaScript syntax. Therefore, we need to translate the data from the PHP representation to the JavaScript representation. The easiest way to do this is to use the JSON format and the json_encode() function, which will turn the object or php array to a string that, when executed by the JavaScript engine, will produce a JavaScript object.

    This is where things can start to get confusing. But there's nothing to worry about. It is enough to remember the sequence. PHP is executed first, then JavaScript. After php execution it will turn out:

    var obj=("test":"123","key":"value"); alert(obj.test);

    Which, when executed, will display an alert with the text “123”.

    Total

    You need to remember that php generates JS, so passing data from it is quite simple. You need to generate JS in the same way as html. Subject to JavaScript syntax.

    An additional request is always used to transfer data from JS to PHP. How it is carried out is the tenth matter. For example, a form can be generated and submitted. Or open an iframe. But the point remains. Understanding this essence, you can transfer any data from the browser to the server and back quite simply.

    So we continue our study again PHP basics and in this article we will get acquainted with ways to pass variables in PHP, namely the GET and POST methods. Each of them has its pros and cons, and is used in appropriate situations, which will be discussed in this article. We'll also look at code examples that demonstrate how the POST and GET methods work.

    Passing Variables Using the GET Method

    This variable passing method is used in PHP to pass variables to a file using the address bar. That is, variables are passed immediately via address bar browser. An example would be, for example, a link to an article in WordPress without using CNC (SEF), which looks something like this:

    https://archive.site/?p=315

    That is, in in this case the $p variable is passed with the value 315. Now let's take a closer look at the GET method using an example. Let's say we need to transfer three variables $a, $b and $c to a file using the GET method and display their sum on the screen. You can use the following code for this.

    $a = $_GET["a"]; $b = $_GET["b"]; $c = $_GET["c"]; $summa = $a + $b + $c; echo "Sum $a + $b + $c = $summa";

    Since all variables will be placed in the global GET() array before transmission, we first assign our variables the values ​​of the corresponding elements of the GET array. We do this at the very beginning to avoid various errors when passing variables. Next, to demonstrate the work, we write an arbitrary formula and display the result on the screen.

    To test the GET method, simply add a question mark “?” to the file link. and through the ampersand “&” list the variables with their values. Let's say we have a file get.php, which is at the root of the site. In order to transfer variables to a file, just write the following in the address bar.

    https://archive.site/get.php?a=1&b=2&c=3

    As you can see from the example, first we add a question mark immediately after the file name. Next, we register the variable and indicate its value using equals. After this, we list other variables in the same way through the ampersand. Now, when we follow this link, we will see the sum of the variables $a, $b and $c.

    This method is very simple and does not require creating additional files. All necessary data comes directly through the address bar of the browser.

    Well, now let's move on to the second method of passing variables in PHP - the POST method.

    Passing Variables to PHP Using the POST Method

    This method allows you to secretly transfer variables from one file to another. As you already understood, two files are usually used for these purposes. The first contains a form for entering initial data, and the second contains an executive file that accepts variables. For demonstration, let's look at the following code.

    Code of the first file with a form for submitting data. Let's give it the name post-1.php

    • action – specify the file to which the variables will be transferred.
    • method – method of passing variables. In our case, this is the POST method.
    • name – name of the form. At the same time, a variable with the same name will be transferred to the file.

    Text fields:

    • name – variable names. In our case, this is the first and last name (name and lastname variables).
    • type – field type. In our case, this is a text field.
    • name – the name of the button and the variable that will be passed along with other variables.
    • type – button type. In our case, this is a button for sending data.
    • value – text on the button.

    The code of the second file, which will serve as a variable receiver. Let's call it post-2.php

    $name = $_POST; $lastname = $_POST; echo "The values ​​of the variables passed by the POST method are $name and $lastname";

    As with the GET method, we first assign the values ​​of the corresponding elements of the global POST array to the variables. Next, for clarity, we display these variables on the screen using .

    Now when we load the first file, the form will load. After entering the data, click on the “Submit” button, as a result of which a page with a second file will open in a new tab, which will display the values ​​​​written in the form on previous page. That is, the values ​​of variables from the first file will be transferred to the second file.

    This concludes this article about passing variables in PHP. If you do not want to miss the appearance of other articles on the blog, I recommend subscribing to the newsletter by any in a convenient way in the “Subscription” section or use the form below.

    That's all. Good luck and success in mastering the basics of PHP.

    Do you know what is false about the concept of “physical vacuum”?

    Physical vacuum is a concept of relativistic quantum physics; it is understood as the lowest (ground) energy state of a quantized field, which has zero momentum, angular momentum and other quantum numbers. Relativistic theorists call a physical vacuum a space completely devoid of matter, filled with an unmeasurable, and therefore only imaginary, field. Such a state, according to relativists, is not an absolute void, but a space filled with some phantom (virtual) particles. Relativistic quantum field theory states that, in accordance with the Heisenberg uncertainty principle, virtual, that is, apparent (apparent to whom?), particles are constantly born and disappeared in the physical vacuum: so-called zero-point field oscillations occur. Virtual particles of the physical vacuum, and therefore itself, by definition, do not have a reference system, since otherwise Einstein’s principle of relativity, on which the theory of relativity is based, would be violated (that is, an absolute measurement system with reference to the particles of the physical vacuum would become possible, which in turn would clearly refute the principle of relativity on which the SRT is based). Thus, the physical vacuum and its particles are not elements of the physical world, but only elements of the theory of relativity that do not exist in real world, but only in relativistic formulas, thereby violating the principle of causality (they arise and disappear without cause), the principle of objectivity (virtual particles can be considered, depending on the desire of the theorist, either existing or non-existent), the principle of factual measurability (not observable, do not have their own ISO ).

    When one or another physicist uses the concept of “physical vacuum,” he either does not understand the absurdity of this term, or is disingenuous, being a hidden or overt adherent of relativistic ideology.

    The easiest way to understand the absurdity of this concept is to turn to the origins of its occurrence. It was born by Paul Dirac in the 1930s, when it became clear that the denial of ether in pure form, as a great mathematician but a mediocre physicist did, is no longer possible. There are too many facts that contradict this.

    To defend relativism, Paul Dirac introduced the aphysical and illogical concept of negative energy, and then the existence of a “sea” of two energies compensating each other in a vacuum - positive and negative, as well as a “sea” of particles compensating each other - virtual (that is, apparent) electrons and positrons in a vacuum.

    8 answers

    HTML/HTTP is stateless, in other words, what you did/saw on the previous page is completely unrelated current page. Except when you're using something like sessions, cookies, or GET/POST. Sessions and cookies are quite easy to use, and the session is much more secure than cookies. More secure, but not completely secure.

    session:

    //On page 1 $_SESSION["varname"] = $var_value; //On page 2 $var_value = $_SESSION["varname"];

    Don't forget to run session_start(); on both of these pages, before attempting to access the $_SESSION array, and also before any output is sent to the browser.

    //One page 1 $_COOKIE["varname"] = $var_value; //On page 2 $var_value = $_COOKIE["varname"];

    A big difference between sessions and cookies is that the value of the variable will be stored on the server if you are using sessions and on the client if you are using cookies. I can't think of any good reason to use cookies instead of sessions, unless you want the data to persist between sessions, but even then it might be better to store it in the DB and retrieve it based on the username or ID.

    GET and POST