Contacts

How to output variable from js to html. Passing variable values ​​from JavaScript to PHP and vice versa. PHP Variables in JavaScript

In this chapter, you'll learn about ActionScript's output methods. By tradition, the string “Hello World” is used as the output data. In this article, we will display this string in three different ways.

The first option for outputting information (the writeln function).

The simplest and most popular way to display information on the screen is the document.writeln(string) function. Below is an example:

< html> < head> < body> < script type= "text/javascript" >document.writeln("Hello World!");

After calling this function, all previously existing page content will be replaced with the new one. In this case, the string "Hello World". Therefore, it is recommended to use this function only when the page is loaded, if all the content is generated by JavaScript. Also, this feature is very useful in situations where it is necessary to reduce the number of calls to the server. Once downloaded, the source file can generate several different pages in a completely offline mode.

The second option for displaying information (the alert function).

The alert(string) function is very good for debugging code, but not for end use. After calling it, a window with an inscription and the “Ok” button will appear in front of the user. It is recommended not to use these pop-ups in real websites, as they are very annoying for visitors and are often blocked by various browser plugins. An example of using the function for debugging:

< html> < head> < body> < script type= "text/javascript" >alert("Hello World!" ) ;

After doing this, when a standard Windows (or Linux, or Mac OS) window appears in front of you with just one answer. No interaction with the page is possible until the “Ok” button is clicked.

The third option for displaying information (the getElementById function).

The most powerful and commonly used way is to use the getElementById(tagId) function.

Everything in HTML code can have an ID parameter. Any tag has a string attached to it (the string can be empty). Through the ID of the tag, you can access its content and, accordingly, change it. In this case, other tags will not be affected. Example:

< html> < head> < body> < div id= "placeForText" > < script type= "text/javascript" >document.getElementById("placeForText" ) .innerHTML = "Hello World!" ;

In this code, first of all, a reference will be made to the document (document), then a pointer to the tag element with id equal to “placeForText” (getElementById(“placeForText”)) is taken, and then, using the innerHTML function, a pointer to the content of this tag element. Using equality, we assign a new value to the content of the element.

This approach is much better than the previous two for two reasons: the absence of annoying pop-up messages, the ability to edit only part of the HTML page. Naturally, when using such a function, the following option is also possible:

< html> < head> < body> < div id= "feedback" > < script type= "text/javascript" >document.getElementById("feedback") .innerHTML = "

Hello World!" ;

When this code is executed, formatted text will be inserted inside the element using HTML tags. That is, we insert HTML inside HTML. The text “Hello World!”, already familiar to us, will appear on the screen, but it will be written in red.

The same mechanism is used on pages with registration of new users. There are two key areas on the page: one is empty, the other with a form that needs to be filled out. If the user skips a field or enters incorrect information and tries to submit the form to the server, then the script responsible for validating the entered data detects an error and displays a red inscription in an empty area without modifying the rest of the page.

Outcome.

In this article, all the main options for displaying text (numbers and other variables represented in text form) on the screen were analyzed. The next article, “JavaScript Cheat Sheet #3 - Entering Information,” will cover the reverse process.

Reg.ru: domains and hosting

The largest registrar and hosting provider in Russia.

Over 2 million domain names in service.

Promotion, mail for domain, solutions for business.

More than 700 thousand customers around the world have already made their choice.

Bootstrap Framework: Fast Responsive Layout

A step-by-step video course on the basics of responsive layout in the Bootstrap framework.

Learn to typeset simply, quickly and efficiently, using a powerful and practical tool.

Make up to order and get money.

Free course "Website on WordPress"

Do you want to master WordPress CMS?

Get lessons on website design and layout on WordPress.

Learn to work with themes and slice the layout.

Free video course on drawing website design, its layout and installation on CMS WordPress!

*Mouseover to pause scrolling.

Back forward

Passing variable values ​​from JavaScript to PHP and vice versa

In this short article, we will consider with you one interesting point regarding the transfer of variable values.

Sometimes it becomes necessary to use the value of a PHP variable in a JavaScript script, or vice versa: there is a JavaScript variable whose value we need to use in a PHP script.

In this tutorial, we will look at simple examples that will allow you to understand the general mechanism of how this can be implemented.

To be specific, I suggest you create a host on your local machine called php_js and place the file there index.php, in which we will consider our examples.

wireframe file index.php there will be simple HTML markup:

Passing Variable Values

For greater clarity, we will write all the code (including JavaScript) inside the tags body.

1. Passing the value of a PHP variable to JavaScript

Let's write this code in the tag body:

1. From PHP to JavaScript:

var userName = ""; document.write("PHP variable value: " + userName);

So we have a PHP variable named name and meaning Yuri, and our task is to display this value on the screen, but not using PHP, but using JavaScript.

To do this, we open a block of JavaScript code as usual and inside it we declare a variable with an arbitrary name (in our case - userName). Now we assign the result of the operation of the operator as a value to this variable echo applied to a variable name.

As you can see, we do this in a block of PHP code that we open and close within single quotes around the variable's string value. userName in a JavaScript script.

Thus, using the PHP language, we form syntactically correct JavaScript code that will be correctly executed.

As a result of executing this line into a variable userName value will fall Yuri.

That's all. PHP variable value name was passed to a JavaScript variable userName.

Now we only need to make sure that in our JavaScript variable userName the expected value is stored. To do this, we display the value of this variable on the screen using document.write.



2. Passing the value of a JavaScript variable to PHP (GET method)

Here, as you understand, the situation is reversed. There is a JavaScript variable available, and its value must somehow be passed to the PHP script.

It is clear that this task is somewhat more complicated, because if in the first case (passing the value of a PHP variable to JavaScript) we already had a PHP variable, the value of which we simply displayed inside the JavaScript code, then this option will not work here.

After all, the PHP script does not know anything about the fact that we have created a certain JavaScript variable. And he will not know about it until we send a GET or POST request to the server, in which the value of the JavaScript variable will appear.

Then, on the next request, we will be able to access the value of this JavaScript variable from the PHP script.

Add the following below the existing code:




2. From JavaScript to PHP (GET method):

var userName2 = "Dmitry";

Inside the JavaScript code block, we create a variable userName2 with meaning Dmitriy.

Here our task is to use PHP to create a correct JavaScript script that will reload the current page and at the same time pass the file index.php via the address bar (i.e. by the GET method) the value contained in the JavaScript variable userName2.

To do this, we display the opening block of JavaScript code on the page using the operator echo, inside which we set by means of JavaScript to reload the current page ( document.location.href).

As the address of the page, we use the value of the element REQUEST_URI from the global array $_SERVER and add a parameter to it with the name u_name and a value equal to the value of the variable userName2.

As a result, our conditional construction if-else works like this:

1. If when accessing the page index.php in the global array $_GET there is an element with index u_name(i.e. the JavaScript redirect worked successfully), then we display the value of the passed JavaScript variable on the screen.

2. If, when accessing the page index.php in the global array $_GET no element at index u_name, then the JavaScript script, generated by PHP, is launched and redirects to the same page, but with the parameter u_name, which has the value of a variable userName2(we talked about this a little higher).

Now, when referring to index.php we get this result:

As you can see, we passed the value of the variable to the address bar using JavaScript userName2. As a result, in the array $_GET there is an element with index u_name and meaning Dmitriy.

The task is solved, and now we can manipulate the received value in any way within the framework of the PHP script, which we did by using the display of the element value u_name from array $_GET.

In the source code of the generated page, we will see the following picture:


We also dealt with this moment, and there was one more option left.


3. Passing the value of a JavaScript variable to PHP (POST method)

In the previous example, we looked at how to pass a value using the browser's address bar (using the GET).

Now we will consider the option of passing a value without using the address bar, i.e. method POST.

In this example, we will use a form to submit data to the server using the method POST.

Below the existing code, write:




3. From JavaScript to PHP (POST method):

var userName3 = "Alexander";

JavaScript variable value:

Our beginning is similar: in a block of JavaScript code, we declare a variable with the name userName3 and meaning Alexander.

After that, we move on to the PHP code. We see that in the branch if checks for existence in the global array $_POST element with index u_name.

If the given element is found, it will be displayed and the paragraph tag for the whole sentence will be closed.

If this element is not present in the array $_POST control is transferred to the branch else.

To do this, we display the opening and closing blocks of JavaScript code on the page using the operator echo, and inside them we form syntactically correct JavaScript code.

Our task is to ensure that, using the output command document.write in JavaScript, display a regular HTML form on the page and substitute it in its only text field with the name u_name the value that is stored in the variable userName3(Alexander).

The hardest part here is not to get confused about the quotes and their escaping.

That is why, before writing such scripts, I recommend that you first create a separate file and write pure JavaScript code in it, which would display the form and substitute the value of the variable in the field userName3.

When you're done with that, you can go back to the original file and your task will be to accurately output the code that you wrote a little earlier. This time - already by means of PHP.

This is exactly what we do in the branch else. Note that the output text (intended for the operator echo) is enclosed in double quotes. Accordingly, for the design document.write we use single quotes.

This circumstance leads to the fact that we need to escape all single quote characters that are between the opening and closing single quotes, limiting the string output for the construction document.write.

If we now turn to the page index.php, then the result will be:

As you can see, after the phrase "JavaScript variable value:" there is an empty space, i.e. the PHP script has not yet received the value of the JavaScript variable userName3. And this is understandable - after all, there has not yet been a request to the server in which this information could be transmitted.

At the same time, below in the form we have the word Alexander- just the value of the JavaScript variable userName3.

We inserted it here just to submit the form and pass the value of this variable to the method POST our current script index.php(if attribute action missing, the data will be passed to the current script).

After clicking on the submit button, we will see the following picture:

Now the form has disappeared from us, because. thread is already running if, and the value of the variable is displayed instead.

Well, we also coped with this task - the value of the JavaScript variable userName3 we passed it to the PHP script and displayed it on the screen from the array $_POST.

This concludes this short article. I really hope that it will help you understand the basic principles of passing variable values ​​from JavaScript to PHP and vice versa.

And then we looked at how to handle user events. This time we're going to look at how to get some user input and put it together with others to make a simple welcome page.

examples/js/pure_js_greating.html

Hello World First name: Last name: Say hi! function say_hi() ( var fname = document.getElementById("first_name").value; var lname = document.getElementById("last_name").value; var html = "Hello " + fname + " " + lname; document.getElementById ("result").innerHTML = html;) document.getElementById("say").addEventListener("click", say_hi); Try!

In this example, we have a little more HTML than before. Besides the button and div where we will show our results, we also have two input elements. Each with its own ID.

In the JavaScript code, we have the say_hi function. It uses the getElementById method we covered earlier to get the DOM element representing the input with id first_name . The returned object has a value method that will return the text entered by the user in that field.

We use this method to get the contents of both input elements and assign the resulting values ​​to two variables: fname and lname .

Then, using these variables, we create an HTML snippet and assign it to the new html variable.

We then set the innerHTML attribute (as we did earlier) to show the generated HTML. The result might look like this:

Cumbersome HTML creation

Even in this simple HTML, we have to use + a few times and the code is quite unreadable. Imagine what would happen if we wanted to create a more complex application where we wanted to generate lists of items or even tables. Generating HTML on the fly and inserting it into the DOM would be pretty nasty.

With a backend written in Perl, Python, or Ruby, people have experienced the same problems. The solution was to create different template engines. Basically, a template is an HTML snippet with some placeholders (keywords), some function receives this HTML snippet (template) as a parameter, and also some key-value pairs. The function then returns a new HTML snippet in which the placeholders have been replaced with the received values ​​of the matching keys.

Displaying text data on the screen in JavaScript is carried out using two operators: Alert and Write.

Alert statement in JavaScript

This way of displaying text (information) in JavaScript is characterized by the fact that a small message box appears on the browser screen - it is also called a dialog box. The characteristic features of the panel are the presence of the Ok button and textual information.

Let's look at an example of displaying a message in JavaScript: Alert("Hi! How are you?") // the corresponding inscription will appear in the dialog panel

It's so easy with the help of the Alert operator in JavaScript, we can output data to the screen (text, pictures, messages).

This method of displaying messages is convenient when the text message is small and does not need formatting. Otherwise, you should use the write statement.

Write Statement in JavaScript

This method is provided by the document object. Therefore, the message output statement will look like this: document.write('Text information') . The text will not be displayed in the dialog box, but in the browser window.

Unlike the first method, we can format our document using HTML language tags. The line with the message will look in this case as if it were part of the HTML page.

Formatting example: document.write(" This is how the text is formatted")

If the message is large, then it can be divided into several substrings using the + symbol. document.write("Separate the message " + " with a +")

Data entry in JavaScript

You can also use two methods to enter data in JavaScript: calling confirm or prompt. Both methods, like alert, work with a dialog box, but have different purposes. The first requires the user to only select one of two options, and the second requires the user to fill out a form.

1. JavaScript confirm statement

When using this operator, the user will see a dialog box on the screen containing some kind of message, and a little lower - two buttons - Ok and Cancel. This method is necessary if the program needs an action from the user - confirmation or refutation of some information.

Let's look at an example of using the confirm statement:

document.write("Going...")

The script works like this:

    Shows the user the message "Are you ready to follow the link?" and waiting for his action.

    If the user presses yes (Ok), then the program displays the message "Going to ...".

    If the user clicks cancel (cancel), then the screen displays "Following the link canceled."

2. The prompt statement in JavaScript

This statement waits for the user not only to click Ok or Cancel, but to fill out some form. The user will see a message and a line in which he should enter data (dates, numbers, messages). If he enters data and clicks Ok, then the prompt method reads the contents of the string and gives it to a variable. Otherwise (when cancel is clicked), the variable is set to null.

So this method has 2 parameters. The first is the text explaining to the user what is required of him. And the second is the value that the variable will get if the user presses (cancel).

Let's look at an example: var s // declare a variable with an undefined primitive

s=prompt("Enter your name", "Name not entered") // two parameters of the prompt operator

document.write(s) //printing the value of a variable

In the process of developing sites, there is often a need to pass some value (variable, array) to javascript, in such cases it is usually advised something like

var variable = alert(variable);

Javascript written inline causes mixed feelings.

Firstly, it is almost always not according to the code style.

Second, it's hard to debug.

Thirdly, such code is not cached by the browser.

Attention dear reader, the example above is more than completely wrong, which I warn you right away and this is exactly how you don’t need to do it, but you can read about how correctly thoughtfully and carefully below.

But if, for example, you are not a person of high moral principles, you can safely copy and do anything with it at all, I did not advise you to do this, and moreover, I even dissuaded you.

I am convinced that javascript should be stored exclusively in files,
html in order to ensure normal browser caching, and make it easier to find this very script in your project.

But how do you pass a value from php and still keep beautiful code?

The answer is to use eval() in Javascript.

Consider an example with google maps connected.

First, let's connect google maps (library)

we initialize the start of drawing maps immediately after loading the DOM

Var $ = jQuery.noConflict(); $(document).ready(function () ( if ($("#map-canvas").length) ( function initialize() ( var place = eval($("#map-canvas").attr("data -place")); var pos = new google.maps.LatLng(place, place); var mapOptions = ( center: pos, zoom: 17, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControlOptions: ( style: google. maps.MapTypeControlStyle.DROPDOWN_MENU ), scrollwheel: false, rotateControl: true ); var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); map.setTilt(45); var marker = new google.maps.Marker(( position: pos, map: map )); ) google.maps.event.addDomListener(window, "load", initialize); ) ));

Let's create the necessary html elements

Explanation of this street magic

in js we are interested in the line:

var place = eval($("#map-canvas").attr("data-place"));

$("#map-canvas").attr("data-place")

Gets the data-place attribute of the element with the id map-canvas, after which eval() converts the string into js code, more specifically into an array. there are square brackets.

According to the HTML5 specification, browsers skip tag attributes starting with data- this attribute will not affect rendering, but its value can be used in javascript.

The html code can be modified:



Liked the article? Share it