Javascript and php code

How to execute PHP code within JavaScript

You can’t. PHP is executed server side, and the finished content is sent to the browser. Javascript just sees the end result. All you can do is make an AJAX call and get the results from that.

did you not search the site before asking the question — this has been asked hundreds of times before. Just look at the list of «Related» questions in the right hand panel.

@andrewsi now you can! (and sorry for making this horrible monster) 🙂 francisco.io/blog/running-php-in-javascript

11 Answers 11

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it’s just echos, and the script is in a php file, you could do something like this:

don’t worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

it would write the contents of test.php to whatever element has the result class.

@Jocelyn yeah, the highlighter here expects all code to be processed by the same thing at the same time.

Interaction of Javascript and PHP

We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

But — good news; it can be made to work and here’s how.

The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed — — typically this implies DHTML modification to the presentation.

First, to clarify the DHTML usage I’ll cite this DHTML example:

Assuming we have an html file with the somewhere, then we can alter the display with a simple

Golly gee; we don’t need PHP to do that now do we! But that creates a structure for applying PHP provided content.

We change the webpage in question into a PHTML type to allow the server side PHP access to the content:

and we add to the top of that page. We also cause the php data to be loaded into globals for later access — — like this:

 else < echo "FAILED!"; >> function returnContent($filename) < if ( $theData = getContent($filename) ) < // this works ONLY if $theData is one linear line (ie remove all \n) $textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData)); return "$textPHP"; >else < echo 'Error opening source file :(\n'; # $filename!\n"; > > // preload the dynamic contents now for use later in the javascript (somewhere) $msg1 = returnContent('dummy_frame_data.txt'); $msg2 = returnContent('dummy_frame_data_0.txt'); $textMsgPHP = returnContent('dummy_frame_data_1.txt'); ?> 

Now our javascripts can get to the PHP globals like this:

In the javascript, replace

var textMsg = ‘Say good night Gracy’;

with: // using php returnContent()

  • the webpage to be modified MUST be a phtml or some php file
  • the first thing in that file MUST be the
  • the php data MUST contain its own css styling (if content is in a frame)
  • the javascript to use the dynamic data must be in this same file
  • and we drop in/outof PHP as necessary to access the dynamic data
  • Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data

To be resolved: calling updateContent() with a filename and using it via onClick() instead of onLoad()

An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn’t find a means to attach it

Источник

Выполнение PHP-кода в файлах JavaScript

В большинстве веб-приложений статические JavaScript-файлы устраивают разработчика на 100%. Однако же иногда бывает лучшим решением подключить PHP и сгенерировать содержимое JS-файла «на лету» (например, получить актуальные цены на продукты из БД и передать их JavaScript-программе для валидации формы заказа). Как же это сделать?

Способ первый: простой

Конечно же, самое простое решение состоит в том, чтобы включить код PHP внутрь секции вашего HTML-шаблона, поскольку есть шансы, что у него будет расширение .php.

Даже если расширение шаблона .htm или .html, то в большинстве случаев веб-сервер настроен так, чтобы понимать включения PHP-кода (если же нет, то в конце заметки есть простой пример как решить и эту проблему). Но что касается красоты, то этот вариант не самый изящный. Хорошо бы держать мух и котлеты раздельно.

Способ второй: красивый

Второй вариант решения — настроить веб-сервер так, чтобы он парсил JavaScript-файлы на предмет выполнения PHP-кода. Достаточно создать в нужной папке файл .htaccess или открыть уже существующий и добавить в него следующие строки:

AddType application/x-httpd-php .js AddHandler x-httpd-php5 .js SetHandler application/x-httpd-php 
Pro et Contra: что нам это дает?
  • Вы можете включать PHP-код в файлы с расширением .js и он автоматически выполнится при клиентском обращении к JavaScript-файлу.
  • Вы можете держать такие «гибридные» скрипты в отдельной папке — достаточно в эту папку поместить описанный выше файл .htaccess.
  • Если вы хотите держать все JavaScript-файлы в одном месте (статические и гибридные), то можете зарегистрировать обработчик файлов с произвольным расширением, например, .js2 — достаточно немного модифицировать текст .htaccess.
  • Вы можете разделить статические HTML-страницы, шаблоны и JavaScript-файлы.
  • Теоретически это вызовет минимальную дополнительную нагрузку на работу сервера, но, учитывая вариации с отдельными папками или расширениями файлов, польза кажется превосходящей.
Дополнение

Для того, чтобы веб-сервер парсил файлы .htm и .html и выполнял включенный в них PHP-код, нужно добавить в .htaccess следующие строки:

AddType application/x-httpd-php .htm .html AddHandler x-httpd-php5 .htm .html SetHandler application/x-httpd-php 

Замечания, дополнения и обмен опытом приветствуются.

ВЫВОДЫ

Довольно странно, что небольшая заметка, которая фактически предлагает всего-навсего сниппет для быстрой реализации конкретной практической задачи вызвала такое бурное обсуждение, по большей части похожее на попытки блеснуть теорией. Знаменитое хабра-сообщество в данном случае самоотверженно линчевало те идеи, которые в заметке в принципе не затрагивались. Хотя надо отдать должное — несколько здоровых мыслей все таки есть. И кроме того — нет «никакой другой роскоши, кроме роскоши человеческого общения» (если верить Экзюпери)))).

Источник

How can you use php in a javascript function [duplicate]

You can’t run PHP code with Javascript. When the user recieves the page, the server will have evaluated and run all PHP code, and taken it out. So for example, this will work:

Because server will have evaluated it to this:

However, you can’t perform any operations in PHP with it.

Will simply have been evaluated to this:

If you wan’t to call a PHP script, you’ll have to call a different page which returns a value from a set of parameters.

This, for example, will work:

$num = $_POST["num"]; echo $num * 2; 

Javascript(jQuery) (on another page):

$.post('script.php', < num: 5 >, function(result) < alert(result); >); 

Edit: Just incrementing a number on the page can be done easily in jQuery like this: http://jsfiddle.net/puVPc/

I think you’re confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I’d recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

Simply, your question sounded wrong because the JavaScript variables need to be echoed.

assign the php value to javascript variable.

    
var numeric = "; //assigns value of the $num to javascript var numeric function Inc()

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

There is a way to run php in client-side javascript (not talking about server-side js here). Don’t know if this is a very good idea, but you can. As some people pointed out you have to keep in mind the php is evaluated on the server and then returned as static stuff to the browser who will then run the javascript with the added data from the server.

You have to tell the server to evaluate the js files as php files, if you are running an apache server you can do this with a htaccess-file like this:

 SetHandler application/x-httpd-php Header set Content-type "application/javascript" 

Edit: On http page request this trick makes files with js extension be parsed by the php compiler. All php parts in the js file will get executed and the js file with added server data will be handed to the browser.

However, the OP uses an html formated file (probably with php extension), no js file, so in this specific case there’s no need for my suggestion.

The suggested js solutions are the way to go. If the variable needs to get stored on the server, use ajax to send it there.

Источник

Читайте также:  If without brackets java
Оцените статью